blob: cbc0790f919326f41a82878a6a690ab3e8d988c9 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
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
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
jioana0bdbea12024-08-10 19:26:04 +000055#include "InputEventTimeline.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000056#include "trace/InputTracer.h"
57#include "trace/InputTracingPerfettoBackend.h"
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000058#include "trace/ThreadedBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010059
Michael Wrightd02c5b62014-02-10 15:10:22 -080060#define INDENT " "
61#define INDENT2 " "
62#define INDENT3 " "
63#define INDENT4 " "
64
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080065using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070066using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080067using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000068using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070070using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050071using android::gui::FocusRequest;
72using android::gui::TouchOcclusionMode;
73using android::gui::WindowInfo;
74using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080075using android::os::InputEventInjectionResult;
76using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000077namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080078
Garfield Tane84e6f92019-08-29 17:28:41 -070079namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
Prabir Pradhancef936d2021-07-21 16:17:52 +000081namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000082
Prabir Pradhandae52792023-12-15 07:36:40 +000083// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
84// flag is enabled. When the flag is changed, tracing will only be available after reboot.
85bool isInputTracingEnabled() {
86 static const std::string buildType = base::GetProperty("ro.build.type", "user");
87 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
88 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
89}
90
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000091// Create the input tracing backend that writes to perfetto from a single thread.
Prabir Pradhanf4099452024-04-12 18:34:14 +000092std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000093 if (!isInputTracingEnabled()) {
94 return nullptr;
95 }
96 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
Prabir Pradhanf4099452024-04-12 18:34:14 +000097 trace::impl::PerfettoBackend());
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000098}
99
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000100template <class Entry>
101void ensureEventTraced(const Entry& entry) {
102 if (!entry.traceTracker) {
103 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
104 }
105}
106
Prabir Pradhan052fb0b2024-02-23 21:03:12 +0000107// Helper to get a trace tracker from a traced key or motion entry.
108const std::unique_ptr<trace::EventTrackerInterface>& getTraceTracker(const EventEntry& entry) {
109 switch (entry.type) {
110 case EventEntry::Type::MOTION: {
111 const auto& motion = static_cast<const MotionEntry&>(entry);
112 ensureEventTraced(motion);
113 return motion.traceTracker;
114 }
115 case EventEntry::Type::KEY: {
116 const auto& key = static_cast<const KeyEntry&>(entry);
117 ensureEventTraced(key);
118 return key.traceTracker;
119 }
120 default: {
121 const static std::unique_ptr<trace::EventTrackerInterface> kNullTracker;
122 return kNullTracker;
123 }
124 }
125}
126
Prabir Pradhancef936d2021-07-21 16:17:52 +0000127// Temporarily releases a held mutex for the lifetime of the instance.
128// Named to match std::scoped_lock
129class scoped_unlock {
130public:
131 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
132 ~scoped_unlock() { mMutex.lock(); }
133
134private:
135 std::mutex& mMutex;
136};
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138// Default input dispatching timeout if there is no focused application or paused window
139// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800140const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
141 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
142 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800144// The default minimum time gap between two user activity poke events.
145const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
146
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800147const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000150constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
151
152// Log a warning when an interception call takes longer than this to process.
153constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154
155// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000156constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
157
jioana24878b52024-09-10 10:13:27 +0000158// Interval at which we should push the atom gathering input event latencies in
159// LatencyAggregatorWithHistograms
160constexpr nsecs_t LATENCY_STATISTICS_PUSH_INTERVAL = 6 * 3600 * 1000000000LL; // 6 hours
161
Antonio Kantekea47acb2021-12-23 12:41:25 -0800162// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000163constexpr int LOGTAG_INPUT_INTERACTION = 62000;
164constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000165constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000166
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000167const ui::Transform kIdentityTransform;
168
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000169inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 return systemTime(SYSTEM_TIME_MONOTONIC);
171}
172
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700173inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000174 if (binder == nullptr) {
175 return "<null>";
176 }
177 return StringPrintf("%p", binder.get());
178}
179
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000180static std::string uidString(const gui::Uid& uid) {
181 return uid.toString();
182}
183
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700184Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700186 case AKEY_EVENT_ACTION_DOWN:
187 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700190 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 }
192}
193
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700194Result<void> validateKeyEvent(int32_t action) {
195 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196}
197
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700198Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800199 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700201 case AMOTION_EVENT_ACTION_UP: {
202 if (pointerCount != 1) {
203 return Error() << "invalid pointer count " << pointerCount;
204 }
205 return {};
206 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700207 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700208 case AMOTION_EVENT_ACTION_HOVER_ENTER:
209 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700210 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
211 if (pointerCount < 1) {
212 return Error() << "invalid pointer count " << pointerCount;
213 }
214 return {};
215 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800216 case AMOTION_EVENT_ACTION_CANCEL:
217 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700218 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700219 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 case AMOTION_EVENT_ACTION_POINTER_DOWN:
221 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800222 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223 if (index < 0) {
224 return Error() << "invalid index " << index << " for "
225 << MotionEvent::actionToString(action);
226 }
227 if (index >= pointerCount) {
228 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
229 }
230 if (pointerCount <= 1) {
231 return Error() << "invalid pointer count " << pointerCount << " for "
232 << MotionEvent::actionToString(action);
233 }
234 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700235 }
236 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700237 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
238 if (actionButton == 0) {
239 return Error() << "action button should be nonzero for "
240 << MotionEvent::actionToString(action);
241 }
242 return {};
243 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700244 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700245 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 }
247}
248
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000249int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500250 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
251}
252
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700253Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
254 const PointerProperties* pointerProperties) {
255 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
256 if (!actionCheck.ok()) {
257 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 }
259 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700260 return Error() << "Motion event has invalid pointer count " << pointerCount
261 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800263 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 for (size_t i = 0; i < pointerCount; i++) {
265 int32_t id = pointerProperties[i].id;
266 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700267 return Error() << "Motion event has invalid pointer id " << id
268 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800270 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700271 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800273 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700275 return {};
276}
277
278Result<void> validateInputEvent(const InputEvent& event) {
279 switch (event.getType()) {
280 case InputEventType::KEY: {
281 const KeyEvent& key = static_cast<const KeyEvent&>(event);
282 const int32_t action = key.getAction();
283 return validateKeyEvent(action);
284 }
285 case InputEventType::MOTION: {
286 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
287 const int32_t action = motion.getAction();
288 const size_t pointerCount = motion.getPointerCount();
289 const PointerProperties* pointerProperties = motion.getPointerProperties();
290 const int32_t actionButton = motion.getActionButton();
291 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
292 }
293 default: {
294 return {};
295 }
296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800297}
298
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800299std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
300 std::bitset<MAX_POINTER_ID + 1> pointerIds;
301 for (const PointerProperties& pointer : pointers) {
302 pointerIds.set(pointer.id);
303 }
304 return pointerIds;
305}
306
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000307std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000309 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 }
311
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000312 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313 bool first = true;
314 Region::const_iterator cur = region.begin();
315 Region::const_iterator const tail = region.end();
316 while (cur != tail) {
317 if (first) {
318 first = false;
319 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800320 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800322 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323 cur++;
324 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000325 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800326}
327
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000328std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
329 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500330 constexpr size_t maxEntries = 50; // max events to print
331 constexpr size_t skipBegin = maxEntries / 2;
332 const size_t skipEnd = queue.size() - maxEntries / 2;
333 // skip from maxEntries / 2 ... size() - maxEntries/2
334 // only print from 0 .. skipBegin and then from skipEnd .. size()
335
336 std::string dump;
337 for (size_t i = 0; i < queue.size(); i++) {
338 const DispatchEntry& entry = *queue[i];
339 if (i >= skipBegin && i < skipEnd) {
340 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
341 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
342 continue;
343 }
344 dump.append(INDENT4);
345 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000346 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
347 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500348 ns2ms(currentTime - entry.eventEntry->eventTime));
349 if (entry.deliveryTime != 0) {
350 // This entry was delivered, so add information on how long we've been waiting
351 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
352 }
353 dump.append("\n");
354 }
355 return dump;
356}
357
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700358/**
359 * Find the entry in std::unordered_map by key, and return it.
360 * If the entry is not found, return a default constructed entry.
361 *
362 * Useful when the entries are vectors, since an empty vector will be returned
363 * if the entry is not found.
364 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
365 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700366template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700368 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700369 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800370}
371
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000372bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700373 if (first == second) {
374 return true;
375 }
376
377 if (first == nullptr || second == nullptr) {
378 return false;
379 }
380
381 return first->getToken() == second->getToken();
382}
383
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000384bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000385 if (first == nullptr || second == nullptr) {
386 return false;
387 }
388 return first->applicationInfo.token != nullptr &&
389 first->applicationInfo.token == second->applicationInfo.token;
390}
391
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800392template <typename T>
393size_t firstMarkedBit(T set) {
394 // TODO: replace with std::countr_zero from <bit> when that's available
395 LOG_ALWAYS_FATAL_IF(set.none());
396 size_t i = 0;
397 while (!set.test(i)) {
398 i++;
399 }
400 return i;
401}
402
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000403std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
404 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000405 std::shared_ptr<const EventEntry> eventEntry,
406 ftl::Flags<InputTarget::Flags> inputTargetFlags,
Prabir Pradhana67623c2024-02-21 06:57:36 +0000407 int64_t vsyncId,
408 trace::InputTracerInterface* tracer) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000409 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000410 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
411 const std::optional<int32_t> windowId =
412 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
413 // Assume the only targets that are not associated with a window are global monitors, and use
414 // the system UID for global monitors for tracing purposes.
415 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000416
417 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700418 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700419 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700420 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000421 inputTarget.globalScaleFactor, uid, vsyncId,
422 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000423 }
424
425 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
426 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
427
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000428 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000429
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000430 const ui::Transform* transform = &kIdentityTransform;
431 const ui::Transform* displayTransform = &kIdentityTransform;
432 if (zeroCoords) {
433 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
434 } else {
435 // Use the first pointer information to normalize all other pointers. This could be any
436 // pointer as long as all other pointers are normalized to the same value and the final
437 // DispatchEntry uses the transform for the normalized pointer.
438 transform =
439 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
440 const ui::Transform inverseTransform = transform->inverse();
441 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000442
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000443 // Iterate through all pointers in the event to normalize against the first.
444 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
445 PointerCoords& newCoords = pointerCoords[i];
446 const auto pointerId = motionEntry.pointerProperties[i].id;
447 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000448
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000449 newCoords.copyFrom(motionEntry.pointerCoords[i]);
450 // First, apply the current pointer's transform to update the coordinates into
451 // window space.
Prabir Pradhan4b8d36c2024-06-07 15:10:46 +0000452 MotionEvent::calculateTransformedCoordsInPlace(newCoords, motionEntry.source,
453 motionEntry.flags, currTransform);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000454 // Next, apply the inverse transform of the normalized coordinates so the
455 // current coordinates are transformed into the normalized coordinate space.
Prabir Pradhan4b8d36c2024-06-07 15:10:46 +0000456 MotionEvent::calculateTransformedCoordsInPlace(newCoords, motionEntry.source,
457 motionEntry.flags, inverseTransform);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000458 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000459 }
460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700461 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000462 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000463 motionEntry.eventTime, motionEntry.deviceId,
464 motionEntry.source, motionEntry.displayId,
465 motionEntry.policyFlags, motionEntry.action,
466 motionEntry.actionButton, motionEntry.flags,
467 motionEntry.metaState, motionEntry.buttonState,
468 motionEntry.classification, motionEntry.edgeFlags,
469 motionEntry.xPrecision, motionEntry.yPrecision,
470 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
471 motionEntry.downTime, motionEntry.pointerProperties,
472 pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +0000473 if (tracer) {
474 combinedMotionEntry->traceTracker =
475 tracer->traceDerivedEvent(*combinedMotionEntry, *motionEntry.traceTracker);
476 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000477
478 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700479 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000480 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000481 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000482 return dispatchEntry;
483}
484
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500485template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000486bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500487 if (lhs == nullptr && rhs == nullptr) {
488 return true;
489 }
490 if (lhs == nullptr || rhs == nullptr) {
491 return false;
492 }
493 return *lhs == *rhs;
494}
495
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000496KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000497 KeyEvent event;
498 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
499 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
500 entry.repeatCount, entry.downTime, entry.eventTime);
501 return event;
502}
503
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000504bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000505 // Do not keep track of gesture monitors. They receive every event and would disproportionately
506 // affect the statistics.
507 if (connection.monitor) {
508 return false;
509 }
510 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
511 if (!connection.responsive) {
512 return false;
513 }
514 return true;
515}
516
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000517bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000518 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
519 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000520 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
521 return false;
522 }
523 // Only track latency for events that originated from hardware
524 if (eventEntry.isSynthesized()) {
525 return false;
526 }
527 const EventEntry::Type& inputEventEntryType = eventEntry.type;
528 if (inputEventEntryType == EventEntry::Type::KEY) {
529 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
530 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
531 return false;
532 }
533 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
534 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
535 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
536 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
537 return false;
538 }
539 } else {
540 // Not a key or a motion
541 return false;
542 }
543 if (!shouldReportMetricsForConnection(connection)) {
544 return false;
545 }
546 return true;
547}
548
Prabir Pradhancef936d2021-07-21 16:17:52 +0000549/**
550 * Connection is responsive if it has no events in the waitQueue that are older than the
551 * current time.
552 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000553bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000554 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000555 for (const auto& dispatchEntry : connection.waitQueue) {
556 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000557 return false;
558 }
559 }
560 return true;
561}
562
Antonio Kantekf16f2832021-09-28 04:39:20 +0000563// Returns true if the event type passed as argument represents a user activity.
564bool isUserActivityEvent(const EventEntry& eventEntry) {
565 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000566 case EventEntry::Type::DEVICE_RESET:
567 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000568 case EventEntry::Type::FOCUS:
569 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000570 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000571 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000572 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000573 case EventEntry::Type::KEY:
574 case EventEntry::Type::MOTION:
575 return true;
576 }
577}
578
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800579// Returns true if the given window can accept pointer events at the given display location.
Linnan Li13bf76a2024-05-05 19:18:02 +0800580bool windowAcceptsTouchAt(const WindowInfo& windowInfo, ui::LogicalDisplayId displayId, float x,
581 float y, bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800582 const auto inputConfig = windowInfo.inputConfig;
583 if (windowInfo.displayId != displayId ||
584 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800585 return false;
586 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700587 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800588 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800589 return false;
590 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000591
592 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
593 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
594 // the window. Points on the right and bottom edges should not be inside the window, so we need
595 // to be careful about performing a hit test when the display is rotated, since the "right" and
596 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
597 // logical display in which WM determined the bounds. Perform the hit test in the logical
598 // display space to ensure these edges are considered correctly in all orientations.
599 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
600 const auto p = displayTransform.transform(x, y);
601 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800602 return false;
603 }
604 return true;
605}
606
Linnan Li5e5645e2024-03-05 14:43:05 +0000607// Returns true if the given window's frame can occlude pointer events at the given display
608// location.
Linnan Li13bf76a2024-05-05 19:18:02 +0800609bool windowOccludesTouchAt(const WindowInfo& windowInfo, ui::LogicalDisplayId displayId, float x,
610 float y, const ui::Transform& displayTransform) {
Linnan Li5e5645e2024-03-05 14:43:05 +0000611 if (windowInfo.displayId != displayId) {
612 return false;
613 }
614 const auto frame = displayTransform.transform(windowInfo.frame);
615 const auto p = floor(displayTransform.transform(x, y));
616 return p.x >= frame.left && p.x < frame.right && p.y >= frame.top && p.y < frame.bottom;
617}
618
Prabir Pradhand65552b2021-10-07 11:23:50 -0700619bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
620 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000621 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700622}
623
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800624// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000625// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
626// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
627// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800628// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000629bool canReceiveForegroundTouches(const WindowInfo& info) {
630 // A non-touchable window can still receive touch events (e.g. in the case of
631 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
632 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
633}
634
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000635bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700636 if (windowHandle == nullptr) {
637 return false;
638 }
639 const WindowInfo* windowInfo = windowHandle->getInfo();
640 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
641 return true;
642 }
643 return false;
644}
645
Prabir Pradhan5735a322022-04-11 17:23:34 +0000646// Checks targeted injection using the window's owner's uid.
647// Returns an empty string if an entry can be sent to the given window, or an error message if the
648// entry is a targeted injection whose uid target doesn't match the window owner.
649std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
650 const EventEntry& entry) {
651 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
652 // The event was not injected, or the injected event does not target a window.
653 return {};
654 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000655 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000656 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000657 return StringPrintf("No valid window target for injection into uid %s.",
658 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000659 }
660 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000661 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
662 "owned by uid %s.",
663 uid.toString().c_str(), window->getName().c_str(),
664 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000665 }
666 return {};
667}
668
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000669std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700670 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
671 // Always dispatch mouse events to cursor position.
672 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000673 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700674 }
675
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700676 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000677 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
678 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700679}
680
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700681std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
682 if (eventEntry.type == EventEntry::Type::KEY) {
683 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
684 return keyEntry.downTime;
685 } else if (eventEntry.type == EventEntry::Type::MOTION) {
686 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
687 return motionEntry.downTime;
688 }
689 return std::nullopt;
690}
691
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000692/**
693 * Compare the old touch state to the new touch state, and generate the corresponding touched
694 * windows (== input targets).
695 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
696 * If the pointer just entered the new window, produce HOVER_ENTER.
697 * For pointers remaining in the window, produce HOVER_MOVE.
698 */
699std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
700 const TouchState& newTouchState,
Siarhei Vishniakouf91f3c72024-08-12 09:58:04 -0700701 const MotionEntry& entry,
702 std::function<void()> dump) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000703 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700704
705 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
706 // ACTION_SCROLL events should not affect the hovering pointer dispatch
707 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000708 }
Linnan Li41859c42024-03-05 16:20:34 +0000709 std::vector<TouchedWindow> out;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000710
711 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800712 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000713
714 std::set<sp<WindowInfoHandle>> oldWindows;
715 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800716 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000717 }
718
719 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800720 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000721
722 // If the pointer is no longer in the new window set, send HOVER_EXIT.
723 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
724 if (newWindows.find(oldWindow) == newWindows.end()) {
725 TouchedWindow touchedWindow;
726 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000727 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000728 out.push_back(touchedWindow);
729 }
730 }
731
732 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
733 TouchedWindow touchedWindow;
734 touchedWindow.windowHandle = newWindow;
735 if (oldWindows.find(newWindow) == oldWindows.end()) {
736 // Any windows that have this pointer now, and didn't have it before, should get
737 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000738 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000739 } else {
740 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700741 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700742 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000743 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
744 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700745 // The Accessibility injected touch exploration event stream
746 // has known inconsistencies, so log ERROR instead of
747 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700748 severity = android::base::LogSeverity::ERROR;
749 }
Siarhei Vishniakouf91f3c72024-08-12 09:58:04 -0700750 dump();
Daniel Norman7487dfa2023-08-02 16:39:45 -0700751 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700752 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000753 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000754 }
Siarhei Vishniakoub711e652024-08-12 12:00:28 -0700755 const auto [x, y] = resolveTouchedPosition(entry);
756 touchedWindow.addHoveringPointer(entry.deviceId, pointer, x, y);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000757 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
758 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
759 }
760 out.push_back(touchedWindow);
761 }
762 return out;
763}
764
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800765template <typename T>
766std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
767 left.insert(left.end(), right.begin(), right.end());
768 return left;
769}
770
Harry Cuttsb166c002023-05-09 13:06:05 +0000771// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
772// both.
773void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
774 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
775 if (!window.windowHandle->getInfo()->inputConfig.test(
776 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
777 // In addition to TouchState, erase this window from the input targets! We don't have a
778 // good way to do this today except by adding a nested loop.
779 // TODO(b/282025641): simplify this code once InputTargets are being identified
780 // separately from TouchedWindows.
781 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800782 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000783 });
784 return true;
785 }
786 return false;
787 });
788}
789
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700790/**
791 * In general, touch should be always split between windows. Some exceptions:
792 * 1. Don't split touch if all of the below is true:
793 * (a) we have an active pointer down *and*
794 * (b) a new pointer is going down that's from the same device *and*
795 * (c) the window that's receiving the current pointer does not support split touch.
796 * 2. Don't split mouse events
797 */
798bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
799 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
800 // We should never split mouse events
801 return false;
802 }
803 for (const TouchedWindow& touchedWindow : touchState.windows) {
804 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
805 // Spy windows should not affect whether or not touch is split.
806 continue;
807 }
808 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
809 continue;
810 }
811 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
812 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
813 // Wallpaper window should not affect whether or not touch is split
814 continue;
815 }
816
817 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
818 return false;
819 }
820 }
821 return true;
822}
823
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700824/**
825 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
826 */
Linnan Li13bf76a2024-05-05 19:18:02 +0800827bool isStylusActiveInDisplay(ui::LogicalDisplayId displayId,
828 const std::unordered_map<ui::LogicalDisplayId /*displayId*/,
829 TouchState>& touchStatesByDisplay) {
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700830 const auto it = touchStatesByDisplay.find(displayId);
831 if (it == touchStatesByDisplay.end()) {
832 return false;
833 }
834 const TouchState& state = it->second;
835 return state.hasActiveStylus();
836}
837
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800838Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
839 struct HashFunction {
840 size_t operator()(const WindowInfo& info) const { return info.id; }
841 };
842
843 std::unordered_set<WindowInfo, HashFunction> windowSet;
844 for (const WindowInfo& info : update.windowInfos) {
845 const auto [_, inserted] = windowSet.insert(info);
846 if (!inserted) {
847 return Error() << "Duplicate entry for " << info;
848 }
849 }
850 return {};
851}
852
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800853int32_t getUserActivityEventType(const EventEntry& eventEntry) {
854 switch (eventEntry.type) {
855 case EventEntry::Type::KEY: {
856 return USER_ACTIVITY_EVENT_BUTTON;
857 }
858 case EventEntry::Type::MOTION: {
859 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
860 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
861 return USER_ACTIVITY_EVENT_TOUCH;
862 }
863 return USER_ACTIVITY_EVENT_OTHER;
864 }
865 default: {
866 LOG_ALWAYS_FATAL("%s events are not user activity",
867 ftl::enum_string(eventEntry.type).c_str());
868 }
869 }
870}
871
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000872std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
873 CancelationOptions::Mode mode) {
874 switch (mode) {
875 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
876 return {true, true};
877 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
878 return {true, false};
879 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
880 return {false, true};
881 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
882 return {false, true};
Siarhei Vishniakoub711e652024-08-12 12:00:28 -0700883 case CancelationOptions::Mode::CANCEL_HOVER_EVENTS:
884 return {true, false};
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000885 }
886}
887
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000888class ScopedSyntheticEventTracer {
889public:
890 ScopedSyntheticEventTracer(std::unique_ptr<trace::InputTracerInterface>& tracer)
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000891 : mTracer(tracer), mProcessingTimestamp(now()) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000892 if (mTracer) {
893 mEventTracker = mTracer->createTrackerForSyntheticEvent();
894 }
895 }
896
897 ~ScopedSyntheticEventTracer() {
898 if (mTracer) {
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000899 mTracer->eventProcessingComplete(*mEventTracker, mProcessingTimestamp);
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000900 }
901 }
902
903 const std::unique_ptr<trace::EventTrackerInterface>& getTracker() const {
904 return mEventTracker;
905 }
906
907private:
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000908 const std::unique_ptr<trace::InputTracerInterface>& mTracer;
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000909 std::unique_ptr<trace::EventTrackerInterface> mEventTracker;
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000910 const nsecs_t mProcessingTimestamp;
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000911};
912
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -0700913/**
914 * This is needed to help use "InputEventInjectionResult" with base::Result.
915 */
916template <typename T>
917struct EnumErrorWrapper {
918 T mVal;
919 EnumErrorWrapper(T&& e) : mVal(std::forward<T>(e)) {}
920 operator const T&() const { return mVal; }
921 T value() const { return mVal; }
922 std::string print() const { return ftl::enum_string(mVal); }
923};
924
925Error<EnumErrorWrapper<InputEventInjectionResult>> injectionError(InputEventInjectionResult&& e) {
926 LOG_ALWAYS_FATAL_IF(e == InputEventInjectionResult::SUCCEEDED);
927 return Error<EnumErrorWrapper<InputEventInjectionResult>>(
928 std::forward<InputEventInjectionResult>(e));
929}
930
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000931} // namespace
932
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933// --- InputDispatcher ---
934
Prabir Pradhana41d2442023-04-20 21:30:40 +0000935InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanf4099452024-04-12 18:34:14 +0000936 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000937
938InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
939 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700940 : mPolicy(policy),
941 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700942 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800943 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800944 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700945 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800946 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700947 mDispatchEnabled(false),
948 mDispatchFrozen(false),
949 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100950 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -0700951 mFocusedDisplayId(ui::LogicalDisplayId::DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800952 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -0700953 mAwaitedApplicationDisplayId(ui::LogicalDisplayId::INVALID),
jioana24878b52024-09-10 10:13:27 +0000954 mInputEventTimelineProcessor(
955 input_flags::enable_per_device_input_latency_metrics()
956 ? std::move(std::unique_ptr<InputEventTimelineProcessor>(
957 new LatencyAggregatorWithHistograms()))
958 : std::move(std::unique_ptr<InputEventTimelineProcessor>(
959 new LatencyAggregator()))),
960 mLatencyTracker(*mInputEventTimelineProcessor) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700961 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800962 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700964 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700965#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700966 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700967#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700968 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000969
970 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000971 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000972 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800973
974 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975}
976
977InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000978 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979
Prabir Pradhancef936d2021-07-21 16:17:52 +0000980 resetKeyRepeatLocked();
981 releasePendingEventLocked();
982 drainInboundQueueLocked();
983 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000985 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700986 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800987 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 }
989}
990
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700991status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700992 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700993 return ALREADY_EXISTS;
994 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700995 mThread = std::make_unique<InputThread>(
Siarhei Vishniakouf53fa6b2024-09-19 17:42:42 -0700996 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); },
997 /*isInCriticalPath=*/true);
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700998 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700999}
1000
1001status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -07001002 if (mThread && mThread->isCallingThread()) {
1003 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -07001004 return INVALID_OPERATION;
1005 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -07001006 mThread.reset();
1007 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07001008}
1009
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -07001011 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08001013 std::scoped_lock _l(mLock);
1014 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015
1016 // Run a dispatch loop if there are no pending commands.
1017 // The dispatch loop might enqueue commands to run afterwards.
1018 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001019 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021
1022 // Run all pending commands if there are any.
1023 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001024 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -07001025 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001027
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001028 // If we are still waiting for ack on some events,
1029 // we might have to wake up earlier to check if an app is anr'ing.
1030 const nsecs_t nextAnrCheck = processAnrsLocked();
1031 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
1032
Asmita Poddar92135902024-09-30 16:10:59 +00001033 if (mPerDeviceInputLatencyMetricsFlag) {
Asmita Poddare0226c52024-10-07 15:22:04 +00001034 processLatencyStatisticsLocked();
jioana24878b52024-09-10 10:13:27 +00001035 }
1036
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001037 // We are about to enter an infinitely long sleep, because we have no commands or
1038 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -07001039 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001040 mDispatcherEnteredIdle.notify_all();
1041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 } // release lock
1043
1044 // Wait for callback or timeout or wake. (make sure we round up, not down)
1045 nsecs_t currentTime = now();
1046 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
1047 mLooper->pollOnce(timeoutMillis);
1048}
1049
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001050/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001051 * Raise ANR if there is no focused window.
1052 * Before the ANR is raised, do a final state check:
1053 * 1. The currently focused application must be the same one we are waiting for.
1054 * 2. Ensure we still don't have a focused window.
1055 */
1056void InputDispatcher::processNoFocusedWindowAnrLocked() {
1057 // Check if the application that we are waiting for is still focused.
1058 std::shared_ptr<InputApplicationHandle> focusedApplication =
1059 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
1060 if (focusedApplication == nullptr ||
1061 focusedApplication->getApplicationToken() !=
1062 mAwaitedFocusedApplication->getApplicationToken()) {
1063 // Unexpected because we should have reset the ANR timer when focused application changed
1064 ALOGE("Waited for a focused window, but focused application has already changed to %s",
1065 focusedApplication->getName().c_str());
1066 return; // The focused application has changed.
1067 }
1068
chaviw98318de2021-05-19 16:45:23 -05001069 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001070 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
1071 if (focusedWindowHandle != nullptr) {
1072 return; // We now have a focused window. No need for ANR.
1073 }
1074 onAnrLocked(mAwaitedFocusedApplication);
1075}
1076
1077/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001078 * Check if any of the connections' wait queues have events that are too old.
1079 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
1080 * Return the time at which we should wake up next.
1081 */
1082nsecs_t InputDispatcher::processAnrsLocked() {
1083 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001084 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001085 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1086 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1087 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001088 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001089 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001090 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001091 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001092 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001093 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001094 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1095 }
1096 }
1097
1098 // Check if any connection ANRs are due
1099 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1100 if (currentTime < nextAnrCheck) { // most likely scenario
1101 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1102 }
1103
1104 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001105 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001106 if (connection == nullptr) {
1107 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1108 return nextAnrCheck;
1109 }
1110 connection->responsive = false;
1111 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001112 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001113 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001114 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001115}
1116
jioana24878b52024-09-10 10:13:27 +00001117/**
1118 * Check if enough time has passed since the last latency statistics push.
jioana24878b52024-09-10 10:13:27 +00001119 */
Asmita Poddare0226c52024-10-07 15:22:04 +00001120void InputDispatcher::processLatencyStatisticsLocked() {
jioana24878b52024-09-10 10:13:27 +00001121 const nsecs_t currentTime = now();
1122 // Log the atom recording latency statistics if more than 6 hours passed from the last
1123 // push
1124 if (currentTime - mLastStatisticPushTime >= LATENCY_STATISTICS_PUSH_INTERVAL) {
1125 mInputEventTimelineProcessor->pushLatencyStatistics();
1126 mLastStatisticPushTime = currentTime;
1127 }
jioana24878b52024-09-10 10:13:27 +00001128}
1129
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001130std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001131 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001132 if (connection->monitor) {
1133 return mMonitorDispatchingTimeout;
1134 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001135 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001136 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001137 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001138 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001139 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001140}
1141
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001142void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 nsecs_t currentTime = now();
1144
Jeff Browndc5992e2014-04-11 01:27:26 -07001145 // Reset the key repeat timer whenever normal dispatch is suspended while the
1146 // device is in a non-interactive state. This is to ensure that we abort a key
1147 // repeat if the device is just coming out of sleep.
1148 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 resetKeyRepeatLocked();
1150 }
1151
1152 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1153 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001154 if (DEBUG_FOCUS) {
1155 ALOGD("Dispatch frozen. Waiting some more.");
1156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 return;
1158 }
1159
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 // Ready to start a new event.
1161 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001163 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 // Synthesize a key repeat if appropriate.
1165 if (mKeyRepeatState.lastKeyEntry) {
1166 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1167 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1168 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001169 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 }
1172
1173 // Nothing to do if there is no pending event.
1174 if (!mPendingEvent) {
1175 return;
1176 }
1177 } else {
1178 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001179 mPendingEvent = mInboundQueue.front();
1180 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 traceInboundQueueLengthLocked();
1182 }
1183
1184 // Poke user activity for this event.
1185 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001186 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 }
1189
1190 // Now we have an event to dispatch.
1191 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001192 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001194 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001196 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001198 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
1200
1201 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001202 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204
1205 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001206 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 const DeviceResetEntry& typedEntry =
1208 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001210 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 break;
1212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001214 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001215 std::shared_ptr<const FocusEntry> typedEntry =
1216 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001217 dispatchFocusLocked(currentTime, typedEntry);
1218 done = true;
1219 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1220 break;
1221 }
1222
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001223 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001224 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001225 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1226 done = true;
1227 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1228 break;
1229 }
1230
Prabir Pradhan99987712020-11-10 18:43:05 -08001231 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1232 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001233 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001234 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1235 done = true;
1236 break;
1237 }
1238
arthurhungb89ccb02020-12-30 16:19:01 +08001239 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001240 std::shared_ptr<const DragEntry> typedEntry =
1241 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001242 dispatchDragLocked(currentTime, typedEntry);
1243 done = true;
1244 break;
1245 }
1246
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001247 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001248 std::shared_ptr<const KeyEntry> keyEntry =
1249 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001251 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001253 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1254 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001256 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 break;
1258 }
1259
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001260 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001261 std::shared_ptr<const MotionEntry> motionEntry =
1262 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001263 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001264 // The event is stale. However, only drop stale events if there isn't an ongoing
1265 // gesture. That would allow us to complete the processing of the current stroke.
1266 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1267 if (touchStateIt != mTouchStatesByDisplay.end()) {
1268 const TouchState& touchState = touchStateIt->second;
1269 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1270 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1271 dropReason = DropReason::STALE;
1272 }
1273 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001274 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001275 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001276 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1277 // Only drop events that are focus-dispatched.
1278 dropReason = DropReason::BLOCKED;
1279 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 }
Chris Yef59a2f42020-10-16 12:55:26 -07001284
1285 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001286 std::shared_ptr<const SensorEntry> sensorEntry =
1287 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001288
Chris Yef59a2f42020-10-16 12:55:26 -07001289 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1290 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1291 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1292 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1293 dropReason = DropReason::STALE;
1294 }
1295 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1296 done = true;
1297 break;
1298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300
1301 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001302 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001303 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 }
Michael Wright3a981722015-06-10 15:26:13 +01001305 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001307 if (mTracer) {
1308 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
Prabir Pradhan4fc32e02024-06-14 16:00:58 +00001309 mTracer->eventProcessingComplete(*traceTracker, currentTime);
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001310 }
1311 }
1312
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001314 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316}
1317
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001318bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001319 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001320}
1321
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001322/**
1323 * Return true if the events preceding this incoming motion event should be dropped
1324 * Return false otherwise (the default behaviour)
1325 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001326bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001327 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001328 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001329
1330 // Optimize case where the current application is unresponsive and the user
1331 // decides to touch a window in a different application.
1332 // If the application takes too long to catch up then we drop all events preceding
1333 // the touch into the other window.
1334 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001335 const ui::LogicalDisplayId displayId = motionEntry.displayId;
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001336 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001337 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001338
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001339 sp<WindowInfoHandle> touchedWindowHandle =
1340 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001341 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001342 touchedWindowHandle->getApplicationToken() !=
1343 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001345 ALOGI("Pruning input queue because user touched a different application while waiting "
1346 "for %s",
1347 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001348 return true;
1349 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001350
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001351 // Alternatively, maybe there's a spy window that could handle this event.
1352 const std::vector<sp<WindowInfoHandle>> touchedSpies =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001353 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, motionEntry.deviceId);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001354 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001355 const std::shared_ptr<Connection> connection =
1356 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001357 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001358 // This spy window could take more input. Drop all events preceding this
1359 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001360 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001361 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001362 mAwaitedFocusedApplication->getName().c_str());
1363 return true;
1364 }
1365 }
1366 }
1367
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001368 return false;
1369}
1370
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001371bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001372 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001373 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001374 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 traceInboundQueueLengthLocked();
1376
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001377 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001378 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001379 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1380 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001382 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001383 if (mTracer) {
1384 ensureEventTraced(keyEntry);
1385 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001386
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001387 // If a new up event comes in, and the pending event with same key code has been asked
1388 // to try again later because of the policy. We have to reset the intercept key wake up
1389 // time for it may have been handled in the policy and could be dropped.
1390 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1391 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001392 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001393 if (pendingKey.keyCode == keyEntry.keyCode &&
1394 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001395 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1396 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001397 pendingKey.interceptKeyWakeupTime = 0;
1398 needWake = true;
1399 }
1400 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 break;
1402 }
1403
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001404 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001405 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1406 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001407 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1408 if (mTracer) {
1409 ensureEventTraced(motionEntry);
1410 }
1411 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001413 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001415
1416 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1417 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1418 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1419 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1420 // and some other events have not yet been processed, the dispatcher will wait for
1421 // these events to be processed before dispatching the key event. This is because
1422 // the unprocessed events may cause the focus to change (for example, by launching a
1423 // new window or tapping a different window). To prevent waiting too long, we force
1424 // the key to be sent to the currently focused window when a new tap comes in.
1425 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1426 "just send the pending key event to the currently focused window.");
1427 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001428 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001429 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001430 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001432 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001433 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1434 break;
1435 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001436 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001437 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001438 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001439 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1440 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001441 // nothing to do
1442 break;
1443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
1445
1446 return needWake;
1447}
1448
Prabir Pradhan24047542023-11-02 17:14:59 +00001449void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001450 // Do not store sensor event in recent queue to avoid flooding the queue.
1451 if (entry->type != EventEntry::Type::SENSOR) {
1452 mRecentQueue.push_back(entry);
1453 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001454 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001455 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 }
1457}
1458
Linnan Li13bf76a2024-05-05 19:18:02 +08001459sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(ui::LogicalDisplayId displayId,
1460 float x, float y, bool isStylus,
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001461 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001463 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001464 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001465 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001466 continue;
1467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001469 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001470 if (!info.isSpy() &&
1471 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001472 return windowHandle;
1473 }
1474 }
1475 return nullptr;
1476}
1477
1478std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08001479 ui::LogicalDisplayId displayId, const sp<WindowInfoHandle>& touchedWindow,
1480 int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001481 if (touchedWindow == nullptr) {
1482 return {};
1483 }
1484 // Traverse windows from front to back until we encounter the touched window.
1485 std::vector<InputTarget> outsideTargets;
1486 const auto& windowHandles = getWindowHandlesLocked(displayId);
1487 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1488 if (windowHandle == touchedWindow) {
1489 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1490 // below the touched window will not get ACTION_OUTSIDE event.
1491 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001492 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001493
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001494 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001495 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001496 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1497 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001498 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1499 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001500 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001503 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504}
1505
Prabir Pradhand65552b2021-10-07 11:23:50 -07001506std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001507 ui::LogicalDisplayId displayId, float x, float y, bool isStylus, DeviceId deviceId) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001508 // Traverse windows from front to back and gather the touched spy windows.
1509 std::vector<sp<WindowInfoHandle>> spyWindows;
1510 const auto& windowHandles = getWindowHandlesLocked(displayId);
1511 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1512 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001513 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001514 // Generally, we would skip any pointer that's outside of the window. However, if the
1515 // spy prevents splitting, and already has some of the pointers from this device, then
1516 // it should get more pointers from the same device, even if they are outside of that
1517 // window
1518 if (info.supportsSplitTouch()) {
1519 continue;
1520 }
1521
1522 // We know that split touch is not supported. Skip this window only if it doesn't have
1523 // any touching pointers for this device already.
1524 if (!windowHasTouchingPointersLocked(windowHandle, deviceId)) {
1525 continue;
1526 }
1527 // If it already has pointers down for this device, then give it this pointer, too.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001528 }
1529 if (!info.isSpy()) {
1530 // The first touched non-spy window was found, so return the spy windows touched so far.
1531 return spyWindows;
1532 }
1533 spyWindows.push_back(windowHandle);
1534 }
1535 return spyWindows;
1536}
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 const char* reason;
1540 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001541 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001542 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001543 ALOGD("Dropped event because policy consumed it.");
1544 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001545 reason = "inbound event was dropped because the policy consumed it";
1546 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001547 case DropReason::DISABLED:
1548 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 ALOGI("Dropped event because input dispatch is disabled.");
1550 }
1551 reason = "inbound event was dropped because input dispatch is disabled";
1552 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001554 LOG(INFO) << "Dropping because the current application is not responding and the user "
1555 "has started interacting with a different application: "
1556 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 reason = "inbound event was dropped because the current application is not responding "
1558 "and the user has started interacting with a different application";
1559 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001560 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 ALOGI("Dropped event because it is stale.");
1562 reason = "inbound event was dropped because it is stale";
1563 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001564 case DropReason::NO_POINTER_CAPTURE:
1565 ALOGI("Dropped event because there is no window with Pointer Capture.");
1566 reason = "inbound event was dropped because there is no window with Pointer Capture";
1567 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001568 case DropReason::NOT_DROPPED: {
1569 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001574 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001575 case EventEntry::Type::KEY: {
Hu Guo3cfa7382023-11-15 09:50:04 +00001576 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001577 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason,
1578 keyEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001579 options.displayId = keyEntry.displayId;
1580 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001584 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001585 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1586 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001587 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason,
1588 motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001589 options.displayId = motionEntry.displayId;
1590 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001591 synthesizeCancelationEventsForAllConnectionsLocked(options);
1592 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001593 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001594 reason, motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001595 options.displayId = motionEntry.displayId;
1596 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 synthesizeCancelationEventsForAllConnectionsLocked(options);
1598 }
1599 break;
1600 }
Chris Yef59a2f42020-10-16 12:55:26 -07001601 case EventEntry::Type::SENSOR: {
1602 break;
1603 }
arthurhungb89ccb02020-12-30 16:19:01 +08001604 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1605 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001606 break;
1607 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001608 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001609 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001610 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001611 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001612 break;
1613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 }
1615}
1616
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001618 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619}
1620
Prabir Pradhancef936d2021-07-21 16:17:52 +00001621bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001622 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 return false;
1624 }
1625
1626 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001627 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001628 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001629 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1630 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001631 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 return true;
1633}
1634
Prabir Pradhancef936d2021-07-21 16:17:52 +00001635void InputDispatcher::postCommandLocked(Command&& command) {
1636 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637}
1638
1639void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001640 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001641 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001642 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 releaseInboundEventLocked(entry);
1644 }
1645 traceInboundQueueLengthLocked();
1646}
1647
1648void InputDispatcher::releasePendingEventLocked() {
1649 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001651 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
1653}
1654
Prabir Pradhan24047542023-11-02 17:14:59 +00001655void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001656 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001657 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001658 if (DEBUG_DISPATCH_CYCLE) {
1659 ALOGD("Injected inbound event was dropped.");
1660 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 }
1663 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001664 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 }
1666 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667}
1668
1669void InputDispatcher::resetKeyRepeatLocked() {
1670 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001671 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
1673}
1674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001675std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001676 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677
Michael Wright2e732952014-09-24 13:26:59 -07001678 uint32_t policyFlags = entry->policyFlags &
1679 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001681 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001682 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1683 currentTime, entry->deviceId, entry->source,
1684 entry->displayId, policyFlags, entry->action, entry->flags,
1685 entry->keyCode, entry->scanCode, entry->metaState,
1686 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001688 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001689 if (mTracer) {
1690 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1691 }
1692
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001693 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001695 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696}
1697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001698bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1699 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001700 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1701 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1702 entry.deviceId);
1703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704
liushenxiang42232912021-05-21 20:24:09 +08001705 // Reset key repeating in case a keyboard device was disabled or enabled.
1706 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1707 resetKeyRepeatLocked();
1708 }
1709
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001710 ScopedSyntheticEventTracer traceContext(mTracer);
1711 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset",
1712 traceContext.getTracker());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001713 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001715
1716 // Remove all active pointers from this device
1717 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1718 touchState.removeAllPointersForDevice(entry.deviceId);
1719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 return true;
1721}
1722
Vishnu Nairad321cd2020-08-20 16:40:21 -07001723void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001724 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001725 if (mPendingEvent != nullptr) {
1726 // Move the pending event to the front of the queue. This will give the chance
1727 // for the pending event to get dispatched to the newly focused window
1728 mInboundQueue.push_front(mPendingEvent);
1729 mPendingEvent = nullptr;
1730 }
1731
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001732 std::unique_ptr<FocusEntry> focusEntry =
1733 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1734 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001735
1736 // This event should go to the front of the queue, but behind all other focus events
1737 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001738 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1739 [](const std::shared_ptr<const EventEntry>& event) {
1740 return event->type == EventEntry::Type::FOCUS;
1741 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001742
1743 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001744 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001745}
1746
Prabir Pradhan24047542023-11-02 17:14:59 +00001747void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1748 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001749 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1750 if (connection == nullptr) {
1751 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001752 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001753 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001754 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001755 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001756 std::string reason = std::string("reason=").append(entry->reason);
1757 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001758 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001759}
1760
Prabir Pradhan99987712020-11-10 18:43:05 -08001761void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001762 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001763 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001764 dropReason = DropReason::NOT_DROPPED;
1765
Prabir Pradhan99987712020-11-10 18:43:05 -08001766 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001767 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001768
Hiroki Sato25040232024-02-22 17:21:22 +09001769 if (entry->pointerCaptureRequest.isEnable()) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001770 // Enable Pointer Capture.
1771 if (haveWindowWithPointerCapture &&
1772 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001773 // This can happen if pointer capture is disabled and re-enabled before we notify the
1774 // app of the state change, so there is no need to notify the app.
1775 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1776 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001777 }
Hiroki Sato25040232024-02-22 17:21:22 +09001778 if (!mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001779 // This can happen if a window requests capture and immediately releases capture.
1780 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001781 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001782 return;
1783 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001784 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1785 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1786 return;
1787 }
1788
Vishnu Nairc519ff72021-01-21 08:23:08 -08001789 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001790 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
Hiroki Sato25040232024-02-22 17:21:22 +09001791 LOG_ALWAYS_FATAL_IF(token != entry->pointerCaptureRequest.window,
1792 "Unexpected requested window for Pointer Capture.");
Prabir Pradhan99987712020-11-10 18:43:05 -08001793 mWindowTokenWithPointerCapture = token;
1794 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001795 // Disable Pointer Capture.
1796 // We do not check if the sequence number matches for requests to disable Pointer Capture
1797 // for two reasons:
1798 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1799 // to disable capture with the same sequence number: one generated by
1800 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1801 // Capture being disabled in InputReader.
1802 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1803 // actual Pointer Capture state that affects events being generated by input devices is
1804 // in InputReader.
1805 if (!haveWindowWithPointerCapture) {
1806 // Pointer capture was already forcefully disabled because of focus change.
1807 dropReason = DropReason::NOT_DROPPED;
1808 return;
1809 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001810 token = mWindowTokenWithPointerCapture;
1811 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001812 if (mCurrentPointerCaptureRequest.isEnable()) {
1813 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001814 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001815 }
1816
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001817 auto connection = getConnectionLocked(token);
1818 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001819 // Window has gone away, clean up Pointer Capture state.
1820 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001821 if (mCurrentPointerCaptureRequest.isEnable()) {
1822 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001823 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001824 return;
1825 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001826 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001827 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001828
1829 dropReason = DropReason::NOT_DROPPED;
1830}
1831
Prabir Pradhan24047542023-11-02 17:14:59 +00001832void InputDispatcher::dispatchTouchModeChangeLocked(
1833 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001834 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001835 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001836 if (windowHandles.empty()) {
1837 return;
1838 }
1839 const std::vector<InputTarget> inputTargets =
1840 getInputTargetsFromWindowHandlesLocked(windowHandles);
1841 if (inputTargets.empty()) {
1842 return;
1843 }
1844 entry->dispatchInProgress = true;
1845 dispatchEventLocked(currentTime, entry, inputTargets);
1846}
1847
1848std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1849 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1850 std::vector<InputTarget> inputTargets;
1851 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001852 const sp<IBinder>& token = handle->getToken();
1853 if (token == nullptr) {
1854 continue;
1855 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001856 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1857 if (connection == nullptr) {
1858 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001859 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001860 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001861 }
1862 return inputTargets;
1863}
1864
Prabir Pradhan24047542023-11-02 17:14:59 +00001865bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001866 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 if (!entry->dispatchInProgress) {
Hu Guofe3c8f12023-09-22 17:20:15 +08001869 if (!entry->syntheticRepeat && entry->action == AKEY_EVENT_ACTION_DOWN &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001870 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1871 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1872 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001873 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 // We have seen two identical key downs in a row which indicates that the device
1875 // driver is automatically generating key repeats itself. We take note of the
1876 // repeat here, but we disable our own next key repeat timer since it is clear that
1877 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001878 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1879 // Make sure we don't get key down from a different device. If a different
1880 // device Id has same key pressed down, the new device Id will replace the
1881 // current one to hold the key repeat with repeat count reset.
1882 // In the future when got a KEY_UP on the device id, drop it and do not
1883 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1885 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001886 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 } else {
1888 // Not a repeat. Save key down state in case we do see a repeat later.
1889 resetKeyRepeatLocked();
1890 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1891 }
1892 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001893 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1894 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001895 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001896 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001897 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1898 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001899 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 resetKeyRepeatLocked();
1901 }
1902
1903 if (entry->repeatCount == 1) {
1904 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1905 } else {
1906 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1907 }
1908
1909 entry->dispatchInProgress = true;
1910
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001911 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
1913
1914 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001915 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001917 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 return false; // wait until next wakeup
1919 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001920 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 entry->interceptKeyWakeupTime = 0;
1922 }
1923
1924 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001925 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001927 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001928 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001929
1930 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1931 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1932 };
1933 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 return false; // wait for the command to run
1935 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001936 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001938 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001939 if (*dropReason == DropReason::NOT_DROPPED) {
1940 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 }
1942 }
1943
1944 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001945 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001946 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1948 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001949 mReporter->reportDroppedKey(entry->id);
Josep del Rioc8fdedb2024-05-21 13:32:43 +00001950 // Poke user activity for consumed keys, as it may have not been reported due to
1951 // the focused window requesting user activity to be disabled
1952 if (*dropReason == DropReason::POLICY &&
1953 mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
1954 pokeUserActivityLocked(*entry);
1955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 return true;
1957 }
1958
1959 // Identify targets.
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001960 Result<sp<WindowInfoHandle>, InputEventInjectionResult> result =
1961 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001963 if (!result.ok()) {
1964 if (result.error().code() == InputEventInjectionResult::PENDING) {
1965 return false;
1966 }
1967 setInjectionResult(*entry, result.error().code());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 return true;
1969 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001970 sp<WindowInfoHandle>& focusedWindow = *result;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001971 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1972
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001973 setInjectionResult(*entry, InputEventInjectionResult::SUCCEEDED);
1974
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001975 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001976 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1977 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001979 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001980 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001982 if (mTracer) {
1983 ensureEventTraced(*entry);
1984 for (const auto& target : inputTargets) {
1985 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1986 }
1987 }
1988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 // Dispatch the key.
1990 dispatchEventLocked(currentTime, entry, inputTargets);
1991 return true;
1992}
1993
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001994void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001995 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001996 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001997 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1998 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Linnan Li13bf76a2024-05-05 19:18:02 +08001999 prefix, entry.eventTime, entry.deviceId, entry.source,
2000 entry.displayId.toString().c_str(), entry.policyFlags, entry.action, entry.flags,
2001 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount, entry.downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003}
2004
Prabir Pradhancef936d2021-07-21 16:17:52 +00002005void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002006 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002007 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002008 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
2009 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
2010 "source=0x%x, sensorType=%s",
2011 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08002012 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002013 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002014 auto command = [this, entry]() REQUIRES(mLock) {
2015 scoped_unlock unlock(mLock);
2016
2017 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00002018 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002019 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00002020 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
2021 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002022 };
2023 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07002024}
2025
2026bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002027 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
2028 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08002029 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002030 }
Chris Yef59a2f42020-10-16 12:55:26 -07002031 { // acquire lock
2032 std::scoped_lock _l(mLock);
2033
2034 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00002035 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07002036 if (entry->type == EventEntry::Type::SENSOR) {
2037 it = mInboundQueue.erase(it);
2038 releaseInboundEventLocked(entry);
2039 }
2040 }
2041 }
2042 return true;
2043}
2044
Prabir Pradhan24047542023-11-02 17:14:59 +00002045bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
2046 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002047 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002048 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 entry->dispatchInProgress = true;
2052
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002053 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
2055
2056 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07002057 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002058 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002059 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
2060 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 return true;
2062 }
2063
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002064 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
2066 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002067 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002069 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 if (isPointerEvent) {
2071 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00002072
2073 if (mDragState &&
2074 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2075 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
2076 pilferPointersLocked(mDragState->dragWindow->getToken());
2077 }
2078
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002079 Result<std::vector<InputTarget>, InputEventInjectionResult> result =
2080 findTouchedWindowTargetsLocked(currentTime, *entry);
2081
2082 if (result.ok()) {
2083 inputTargets = std::move(*result);
2084 injectionResult = InputEventInjectionResult::SUCCEEDED;
2085 } else {
2086 injectionResult = result.error().code();
2087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 } else {
2089 // Non touch event. (eg. trackball)
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002090 Result<sp<WindowInfoHandle>, InputEventInjectionResult> result =
2091 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime);
2092 if (result.ok()) {
2093 sp<WindowInfoHandle>& focusedWindow = *result;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002094 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002095 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2096 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2097 inputTargets);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002098 injectionResult = InputEventInjectionResult::SUCCEEDED;
2099 } else {
2100 injectionResult = result.error().code();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 return false;
2105 }
2106
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002107 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002108 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002109 return true;
2110 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002111 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002112 CancelationOptions::Mode mode(
2113 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2114 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002115 CancelationOptions options(mode, "input event injection failed", entry->traceTracker);
Linnan Lid8150952024-01-26 18:07:17 +00002116 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002117 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 return true;
2119 }
2120
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002121 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002122 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002124 if (mTracer) {
2125 ensureEventTraced(*entry);
2126 for (const auto& target : inputTargets) {
2127 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2128 }
2129 }
2130
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 dispatchEventLocked(currentTime, entry, inputTargets);
2133 return true;
2134}
2135
chaviw98318de2021-05-19 16:45:23 -05002136void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002137 bool isExiting, const int32_t rawX,
2138 const int32_t rawY) {
2139 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002140 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002141 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2142 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002143
2144 enqueueInboundEventLocked(std::move(dragEntry));
2145}
2146
Prabir Pradhan24047542023-11-02 17:14:59 +00002147void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2148 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002149 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2150 if (connection == nullptr) {
2151 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002152 }
arthurhungb89ccb02020-12-30 16:19:01 +08002153 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002154 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002155}
2156
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002157void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002158 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002159 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002160 "action=%s, actionButton=0x%x, flags=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002161 "metaState=0x%x, buttonState=0x%x, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002162 prefix, entry.eventTime, entry.deviceId,
Linnan Li13bf76a2024-05-05 19:18:02 +08002163 inputEventSourceToString(entry.source).c_str(), entry.displayId.toString().c_str(),
2164 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002165 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002167 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002168 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002169 "x=%f, y=%f, pressure=%f, size=%f, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002170 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002171 i, entry.pointerProperties[i].id,
2172 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002173 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2174 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2175 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2176 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2177 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2178 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2179 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2180 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2181 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184}
2185
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002186void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002187 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002189 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002190 if (DEBUG_DISPATCH_CYCLE) {
2191 ALOGD("dispatchEventToCurrentInputTargets");
2192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002194 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002195
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002198 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002200 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002201 std::shared_ptr<Connection> connection = inputTarget.connection;
2202 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
2204}
2205
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002206void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002207 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2208 // If the policy decides to close the app, we will get a channel removal event via
2209 // unregisterInputChannel, and will clean up the connection that way. We are already not
2210 // sending new pointers to the connection when it blocked, but focused events will continue to
2211 // pile up.
2212 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002213 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002214 if (connection->status != Connection::Status::NORMAL) {
2215 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002217 ScopedSyntheticEventTracer traceContext(mTracer);
Prabir Pradhanfc364722024-02-08 17:51:20 +00002218 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002219 "application not responding", traceContext.getTracker());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002220
2221 sp<WindowInfoHandle> windowHandle;
2222 if (!connection->monitor) {
2223 windowHandle = getWindowHandleLocked(connection->getToken());
2224 if (windowHandle == nullptr) {
2225 // The window that is receiving this ANR was removed, so there is no need to generate
2226 // cancellations, because the cancellations would have already been generated when
2227 // the window was removed.
2228 return;
2229 }
2230 }
2231 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232}
2233
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002235 if (DEBUG_FOCUS) {
2236 ALOGD("Resetting ANR timeouts.");
2237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
2239 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002241 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242}
2243
Tiger Huang721e26f2018-07-24 22:26:19 +08002244/**
2245 * Get the display id that the given event should go to. If this event specifies a valid display id,
2246 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2247 * Focused display is the display that the user most recently interacted with.
2248 */
Linnan Li13bf76a2024-05-05 19:18:02 +08002249ui::LogicalDisplayId InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002250 ui::LogicalDisplayId displayId{ui::LogicalDisplayId::INVALID};
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002251 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002252 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002253 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2254 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002255 break;
2256 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002257 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002258 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2259 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002260 break;
2261 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002262 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002263 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002264 case EventEntry::Type::FOCUS:
Chris Yef59a2f42020-10-16 12:55:26 -07002265 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002266 case EventEntry::Type::SENSOR:
2267 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002268 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002269 return ui::LogicalDisplayId::INVALID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002271 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002272 return displayId == ui::LogicalDisplayId::INVALID ? mFocusedDisplayId : displayId;
Tiger Huang721e26f2018-07-24 22:26:19 +08002273}
2274
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002275bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2276 const char* focusedWindowName) {
2277 if (mAnrTracker.empty()) {
2278 // already processed all events that we waited for
2279 mKeyIsWaitingForEventsTimeout = std::nullopt;
2280 return false;
2281 }
2282
2283 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2284 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002285 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002286 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002287 std::chrono::duration_cast<std::chrono::nanoseconds>(
2288 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002289 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002290 return true;
2291 }
2292
2293 // We still have pending events, and already started the timer
2294 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2295 return true; // Still waiting
2296 }
2297
2298 // Waited too long, and some connection still hasn't processed all motions
2299 // Just send the key to the focused window
2300 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2301 focusedWindowName);
2302 mKeyIsWaitingForEventsTimeout = std::nullopt;
2303 return false;
2304}
2305
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002306Result<sp<WindowInfoHandle>, InputEventInjectionResult>
2307InputDispatcher::findFocusedWindowTargetLocked(nsecs_t currentTime, const EventEntry& entry,
2308 nsecs_t& nextWakeupTime) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002309 ui::LogicalDisplayId displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002310 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002311 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002312 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2313
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // If there is no currently focused window and no focused application
2315 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002316 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2317 ALOGI("Dropping %s event because there is no focused window or focused application in "
Linnan Li13bf76a2024-05-05 19:18:02 +08002318 "display %s.",
2319 ftl::enum_string(entry.type).c_str(), displayId.toString().c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002320 return injectionError(InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322
Vishnu Nair062a8672021-09-03 16:07:44 -07002323 // Drop key events if requested by input feature
2324 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002325 return injectionError(InputEventInjectionResult::FAILED);
Vishnu Nair062a8672021-09-03 16:07:44 -07002326 }
2327
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002328 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2329 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2330 // start interacting with another application via touch (app switch). This code can be removed
2331 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2332 // an app is expected to have a focused window.
2333 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2334 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2335 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002336 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2337 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2338 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002339 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002340 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002341 ALOGW("Waiting because no window has focus but %s may eventually add a "
2342 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002343 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002344 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002345 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002346 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2347 // Already raised ANR. Drop the event
2348 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002349 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002350 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002351 } else {
2352 // Still waiting for the focused window
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002353 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002354 }
2355 }
2356
2357 // we have a valid, non-null focused window
2358 resetNoFocusedWindowTimeoutLocked();
2359
Prabir Pradhan5735a322022-04-11 17:23:34 +00002360 // Verify targeted injection.
2361 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2362 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002363 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 }
2365
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002366 if (focusedWindowHandle->getInfo()->inputConfig.test(
2367 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002368 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002369 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002370 }
2371
2372 // If the event is a key event, then we must wait for all previous events to
2373 // complete before delivering it because previous events may have the
2374 // side-effect of transferring focus to a different window and we want to
2375 // ensure that the following keys are sent to the new window.
2376 //
2377 // Suppose the user touches a button in a window then immediately presses "A".
2378 // If the button causes a pop-up window to appear then we want to ensure that
2379 // the "A" key is delivered to the new pop-up window. This is because users
2380 // often anticipate pending UI changes when typing on a keyboard.
2381 // To obtain this behavior, we must serialize key events with respect to all
2382 // prior input events.
2383 if (entry.type == EventEntry::Type::KEY) {
2384 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002385 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002386 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002389 // Success!
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002390 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391}
2392
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002393/**
2394 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2395 * that are currently unresponsive.
2396 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002397std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2398 const std::vector<Monitor>& monitors) const {
2399 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002400 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002401 [](const Monitor& monitor) REQUIRES(mLock) {
2402 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002403 if (!connection->responsive) {
2404 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002405 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002406 return false;
2407 }
2408 return true;
2409 });
2410 return responsiveMonitors;
2411}
2412
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002413base::Result<std::vector<InputTarget>, android::os::InputEventInjectionResult>
2414InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry& entry) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002415 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002417 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 // For security reasons, we defer updating the touch state until we are sure that
2419 // event injection will be allowed.
Linnan Li13bf76a2024-05-05 19:18:02 +08002420 const ui::LogicalDisplayId displayId = entry.displayId;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002422 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002424 // Copy current touch state into tempTouchState.
2425 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2426 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002427 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002428 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002429 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2430 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002431 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002432 }
2433
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002434 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002435
2436 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2437 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2438 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002439 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2440 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002441 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002442 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2443 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002444 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2445 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2446 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002447 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002448
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002449 if (newGesture) {
2450 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002451 }
2452
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002453 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2454 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2455 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002458 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002459 if (wasDown) {
2460 // Started hovering, but the device is already down: reject the hover event
2461 LOG(ERROR) << "Got hover event " << entry.getDescription()
2462 << " but the device is already down " << oldState->dump();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002463 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002464 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002465 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2466 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002467 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002468 }
2469
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2471 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002472 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002473 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002474 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002475 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2476 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002477 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002478 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002479 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002480
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002481 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002482 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002483 }
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07002484 LOG_IF(INFO, newTouchedWindowHandle == nullptr)
2485 << "No new touched window at (" << std::format("{:.1f}, {:.1f}", x, y)
2486 << ") in display " << displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 // Handle the case where we did not find a window.
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07002488 if (!input_flags::split_all_touches()) {
2489 // If we are force splitting all touches, then touches outside of the window should
2490 // be dropped, even if this device already has pointers down in another window.
2491 if (newTouchedWindowHandle == nullptr) {
2492 // Try to assign the pointer to the first foreground window we find, if there is
2493 // one.
2494 newTouchedWindowHandle =
2495 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
2496 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002497 }
2498
Prabir Pradhan5735a322022-04-11 17:23:34 +00002499 // Verify targeted injection.
2500 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2501 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002502 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002503 }
2504
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002505 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002506 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002507 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2508 // New window supports splitting, but we should never split mouse events.
2509 isSplit = !isFromMouse;
2510 } else if (isSplit) {
2511 // New window does not support splitting but we have already split events.
2512 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002513 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2514 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002515 newTouchedWindowHandle = nullptr;
2516 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002517 } else {
2518 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002519 // be delivered to a new window which supports split touch. Pointers from a mouse device
2520 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002521 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002522 }
2523
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002524 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07002525 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, entry.deviceId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002526 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002527 // Process the foreground window first so that it is the first to receive the event.
2528 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002529 }
2530
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002531 if (newTouchedWindows.empty()) {
Siarhei Vishniakouac42d242024-06-28 10:43:53 -07002532 LOG(INFO) << "Dropping event because there is no touchable window at (" << x << ", "
2533 << y << ") on display " << displayId << ": " << entry;
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002534 return injectionError(InputEventInjectionResult::FAILED);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002535 }
2536
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002537 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002538 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002539 continue;
2540 }
2541
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002542 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002543 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakoub711e652024-08-12 12:00:28 -07002544 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer, x,
2545 y);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002546 }
2547
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002548 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002549 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002550
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002551 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2552 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002553 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002554 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002555
2556 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002557 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002558 }
2559 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002561 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002562 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002563 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002564
2565 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002566
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002567 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002568 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2569 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Siarhei Vishniakoue535f972024-03-29 14:55:21 -07002570 Result<void> addResult =
2571 tempTouchState.addOrUpdateWindow(windowHandle,
2572 InputTarget::DispatchMode::AS_IS,
2573 targetFlags, entry.deviceId, {pointer},
2574 isDownOrPointerDown
2575 ? std::make_optional(
2576 entry.eventTime)
2577 : std::nullopt);
2578 if (!addResult.ok()) {
2579 LOG(ERROR) << "Error while processing " << entry << " for "
2580 << windowHandle->getName();
2581 logDispatchStateLocked();
2582 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002583 // If this is the pointer going down and the touched window has a wallpaper
2584 // then also add the touched wallpaper windows so they are locked in for the
2585 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2586 // SCROLL because the wallpaper engine only supports touch events. We would need to
2587 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2588 // handle these events.
2589 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002590 windowHandle->getInfo()->inputConfig.test(
2591 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2592 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2593 if (wallpaper != nullptr) {
2594 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2595 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002596 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002597 if (isSplit) {
2598 wallpaperFlags |= InputTarget::Flags::SPLIT;
2599 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002600 tempTouchState.addOrUpdateWindow(wallpaper,
2601 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002602 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002603 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002604 }
2605 }
2606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002608
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002609 // If a window is already pilfering some pointers, give it this new pointer as well and
2610 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2611 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002612 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002613 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002614 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002615 // This window is already pilfering some pointers, and this new pointer is also
2616 // going to it. Therefore, take over this pointer and don't give it to anyone
2617 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002618 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002619 }
2620 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002621
2622 // Restrict all pilfered pointers to the pilfering windows.
2623 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 } else {
2625 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2626
2627 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002628 if (!tempTouchState.isDown(entry.deviceId) &&
2629 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002630 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2631 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2632 << " is not down or we previously dropped the pointer down event in "
2633 << "display " << displayId << ": " << entry.getDescription();
2634 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002635 return injectionError(InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 }
2637
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002638 // If the pointer is not currently hovering, then ignore the event.
2639 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2640 const int32_t pointerId = entry.pointerProperties[0].id;
2641 if (oldState == nullptr ||
2642 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2643 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2644 "display "
2645 << displayId << ": " << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002646 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002647 }
2648 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2649 }
2650
arthurhung6d4bed92021-03-17 11:59:33 +08002651 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002652
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002654 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Linnan Li49b2b202024-04-12 12:46:40 +08002655 tempTouchState.isSlippery(entry.deviceId)) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002656 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002657 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002658 sp<WindowInfoHandle> oldTouchedWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002659 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002660 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002661 sp<WindowInfoHandle> newTouchedWindowHandle =
2662 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002663
Prabir Pradhan5735a322022-04-11 17:23:34 +00002664 // Verify targeted injection.
2665 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2666 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002667 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002668 }
2669
Linnan Libf069a32024-02-29 17:22:59 +00002670 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002671 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002672 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002673 newTouchedWindowHandle = nullptr;
2674 }
2675
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002676 if (newTouchedWindowHandle != nullptr &&
2677 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002678 ALOGI("Touch is slipping out of window %s into window %s in display %s",
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002679 oldTouchedWindowHandle->getName().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08002680 newTouchedWindowHandle->getName().c_str(), displayId.toString().c_str());
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002681
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002683 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002684 const PointerProperties& pointer = entry.pointerProperties[0];
2685 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002686
2687 const TouchedWindow& touchedWindow =
2688 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002689 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002690 InputTarget::DispatchMode::SLIPPERY_EXIT,
2691 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 touchedWindow.getDownTimeInTarget(entry.deviceId),
2693 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694
2695 // Make a slippery entrance into the new window.
2696 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002697 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002700 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002701 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002702 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002705 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 }
2707 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002708 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002709 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002710 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
2712
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002713 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2714 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002715 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002716 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002717
2718 // Check if the wallpaper window should deliver the corresponding event.
2719 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00002720 tempTouchState, entry, targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002721 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002722 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 }
2724 }
Arthur Hung96483742022-11-15 03:30:48 +00002725
2726 // Update the pointerIds for non-splittable when it received pointer down.
2727 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2728 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002729 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002730 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2731 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002732 // Ignore drag window for it should just track one pointer.
2733 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2734 continue;
2735 }
Siarhei Vishniakou96204462024-07-13 23:59:47 -07002736 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
2737 continue;
2738 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002739 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002740 }
2741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002744 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002745 {
2746 std::vector<TouchedWindow> hoveringWindows =
Siarhei Vishniakouf91f3c72024-08-12 09:58:04 -07002747 getHoveringWindowsLocked(oldState, tempTouchState, entry,
Siarhei Vishniakou8a69ace2024-08-13 18:04:40 +00002748 std::bind_front(&InputDispatcher::logDispatchStateLocked,
2749 this));
Linnan Li41859c42024-03-05 16:20:34 +00002750 // Hardcode to single hovering pointer for now.
2751 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2752 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002753 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002754 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2755 touchedWindow.targetFlags, pointerIds,
2756 touchedWindow.getDownTimeInTarget(entry.deviceId),
2757 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760
Prabir Pradhan5735a322022-04-11 17:23:34 +00002761 // Ensure that all touched windows are valid for injection.
2762 if (entry.injectionState != nullptr) {
2763 std::string errs;
2764 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002765 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2766 if (err) errs += "\n - " + *err;
2767 }
2768 if (!errs.empty()) {
2769 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002770 "%s:%s",
2771 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002772 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002773 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002774 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002775
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002776 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2777 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002779 sp<WindowInfoHandle> foregroundWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002780 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Michael Wright3dd60e22019-03-27 22:06:44 +00002781 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002782 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002783 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002784 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002785 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002786 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002787 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2788 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
2791 }
2792 }
2793 }
2794
Harry Cuttsb166c002023-05-09 13:06:05 +00002795 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2796 // only want the system UI to handle these gestures.
2797 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2798 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2799 if (isTouchpadNavGesture) {
2800 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2801 }
2802
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002803 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002804 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002805 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002806 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002807 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002808 continue;
2809 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002810 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002811 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002812 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002813 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002814
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002815 // During targeted injection, only allow owned targets to receive events
2816 std::erase_if(targets, [&](const InputTarget& target) {
2817 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2818 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2819 if (err) {
2820 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2821 << ": " << (*err);
2822 return true;
2823 }
2824 return false;
2825 });
2826
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002827 if (targets.empty()) {
2828 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002829 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002830 }
2831
2832 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2833 // window that is actually receiving the entire gesture.
2834 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002835 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002836 })) {
2837 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2838 << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002839 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002840 }
2841
Prabir Pradhan502a7252023-12-01 16:11:24 +00002842 // Now that we have generated all of the input targets for this event, reset the dispatch
2843 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002844 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002845 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002846 }
2847
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002848 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002849 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002850 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002851 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002852 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002853 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002854 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002855 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2856 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002857 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2858 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2859 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 }
2861
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002862 // Save changes unless the action was scroll in which case the temporary touch
2863 // state was only valid for this one action.
2864 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002865 if (displayId >= ui::LogicalDisplayId::DEFAULT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002866 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002867 mTouchStatesByDisplay[displayId] = tempTouchState;
2868 } else {
2869 mTouchStatesByDisplay.erase(displayId);
2870 }
2871 }
2872
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002873 if (tempTouchState.windows.empty()) {
2874 mTouchStatesByDisplay.erase(displayId);
2875 }
2876
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002877 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878}
2879
Linnan Li13bf76a2024-05-05 19:18:02 +08002880void InputDispatcher::finishDragAndDrop(ui::LogicalDisplayId displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002881 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2882 // have an explicit reason to support it.
2883 constexpr bool isStylus = false;
2884
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002885 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002886 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002887 if (dropWindow) {
2888 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002889 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002890 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002891 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002892 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002893 }
2894 mDragState.reset();
2895}
2896
2897void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002898 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002899 return;
2900 }
2901
arthurhung6d4bed92021-03-17 11:59:33 +08002902 if (!mDragState->isStartDrag) {
2903 mDragState->isStartDrag = true;
2904 mDragState->isStylusButtonDownAtStart =
2905 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2906 }
2907
Arthur Hung54745652022-04-20 07:17:41 +00002908 // Find the pointer index by id.
2909 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002910 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002911 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2912 if (pointerProperties.id == mDragState->pointerId) {
2913 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002914 }
Arthur Hung54745652022-04-20 07:17:41 +00002915 }
arthurhung6d4bed92021-03-17 11:59:33 +08002916
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002917 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002918 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002919 }
2920
2921 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2922 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2923 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2924
2925 switch (maskedAction) {
2926 case AMOTION_EVENT_ACTION_MOVE: {
2927 // Handle the special case : stylus button no longer pressed.
2928 bool isStylusButtonDown =
2929 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2930 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2931 finishDragAndDrop(entry.displayId, x, y);
2932 return;
2933 }
2934
2935 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2936 // until we have an explicit reason to support it.
2937 constexpr bool isStylus = false;
2938
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002939 sp<WindowInfoHandle> hoverWindowHandle =
2940 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2941 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002942 // enqueue drag exit if needed.
2943 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2944 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2945 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002946 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002947 y);
2948 }
2949 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2950 }
2951 // enqueue drag location if needed.
2952 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002953 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002954 }
2955 break;
2956 }
2957
2958 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002959 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002960 break;
2961 }
2962 // The drag pointer is up.
2963 [[fallthrough]];
2964 case AMOTION_EVENT_ACTION_UP:
2965 finishDragAndDrop(entry.displayId, x, y);
2966 break;
2967 case AMOTION_EVENT_ACTION_CANCEL: {
2968 ALOGD("Receiving cancel when drag and drop.");
2969 sendDropWindowCommandLocked(nullptr, 0, 0);
2970 mDragState.reset();
2971 break;
2972 }
arthurhungb89ccb02020-12-30 16:19:01 +08002973 }
2974}
2975
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002976std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2977 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002978 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002979 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002980 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2981 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002982 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2983 return {};
2984 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002985 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002986 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002987 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002988 inputTarget.flags = targetFlags;
2989 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2990 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2991 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2992 if (displayInfoIt != mDisplayInfos.end()) {
2993 inputTarget.displayTransform = displayInfoIt->second.transform;
2994 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002995 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002996 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2997 }
2998 return inputTarget;
2999}
3000
chaviw98318de2021-05-19 16:45:23 -05003001void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003002 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003004 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07003005 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003006 std::vector<InputTarget>::iterator it =
3007 std::find_if(inputTargets.begin(), inputTargets.end(),
3008 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003009 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003010 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00003011
chaviw98318de2021-05-19 16:45:23 -05003012 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003013
3014 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003015 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003016 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3017 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003018 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003019 return;
3020 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003021 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003022 it = inputTargets.end() - 1;
3023 }
3024
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003025 if (it->flags != targetFlags) {
3026 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
3027 }
3028 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
3029 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
3030 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3031 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003032}
3033
3034void InputDispatcher::addPointerWindowTargetLocked(
3035 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003036 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
3037 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
3038 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003039 if (pointerIds.none()) {
3040 for (const auto& target : inputTargets) {
3041 LOG(INFO) << "Target: " << target;
3042 }
3043 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
3044 return;
3045 }
3046 std::vector<InputTarget>::iterator it =
3047 std::find_if(inputTargets.begin(), inputTargets.end(),
3048 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003049 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003050 });
3051
3052 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
3053 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
3054 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
3055 // input targets for hovering pointers and for touching pointers.
3056 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
3057 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003058 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003059 // Force the code below to create a new input target
3060 it = inputTargets.end();
3061 }
3062
3063 const WindowInfo* windowInfo = windowHandle->getInfo();
3064
3065 if (it == inputTargets.end()) {
3066 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003067 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3068 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003069 if (!target) {
3070 return;
3071 }
3072 inputTargets.push_back(*target);
3073 it = inputTargets.end() - 1;
3074 }
3075
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003076 if (it->dispatchMode != dispatchMode) {
3077 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
3078 << ftl::enum_string(dispatchMode) << ", it=" << *it;
3079 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003080 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003081 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
3082 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003083 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003084 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003085 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003086 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3087 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003088
Siarhei Vishniakou59967592024-04-01 16:17:46 -07003089 Result<void> result = it->addPointers(pointerIds, windowInfo->transform);
3090 if (!result.ok()) {
3091 logDispatchStateLocked();
3092 LOG(FATAL) << result.error().message();
3093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094}
3095
Michael Wright3dd60e22019-03-27 22:06:44 +00003096void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Linnan Li13bf76a2024-05-05 19:18:02 +08003097 ui::LogicalDisplayId displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003098 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3099 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003100
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003101 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003102 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003103 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3104 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003105 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3106 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003107 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003108 target.setDefaultPointerTransform(target.displayTransform);
3109 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 }
3111}
3112
Robert Carrc9bf1d32020-04-13 17:21:08 -07003113/**
3114 * Indicate whether one window handle should be considered as obscuring
3115 * another window handle. We only check a few preconditions. Actually
3116 * checking the bounds is left to the caller.
3117 */
chaviw98318de2021-05-19 16:45:23 -05003118static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3119 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003120 // Compare by token so cloned layers aren't counted
3121 if (haveSameToken(windowHandle, otherHandle)) {
3122 return false;
3123 }
3124 auto info = windowHandle->getInfo();
3125 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003126 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003127 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003128 } else if (otherInfo->alpha == 0 &&
3129 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003130 // Those act as if they were invisible, so we don't need to flag them.
3131 // We do want to potentially flag touchable windows even if they have 0
3132 // opacity, since they can consume touches and alter the effects of the
3133 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003134 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003135 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3136 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003137 } else if (info->ownerUid == otherInfo->ownerUid) {
3138 // If ownerUid is the same we don't generate occlusion events as there
3139 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003140 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003141 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003142 return false;
3143 } else if (otherInfo->displayId != info->displayId) {
3144 return false;
3145 }
3146 return true;
3147}
3148
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003149/**
3150 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3151 * untrusted, one should check:
3152 *
3153 * 1. If result.hasBlockingOcclusion is true.
3154 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3155 * BLOCK_UNTRUSTED.
3156 *
3157 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3158 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3159 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3160 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3161 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3162 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3163 *
3164 * If neither of those is true, then it means the touch can be allowed.
3165 */
3166InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
Linnan Li5e5645e2024-03-05 14:43:05 +00003167 const sp<WindowInfoHandle>& windowHandle, float x, float y) const {
chaviw98318de2021-05-19 16:45:23 -05003168 const WindowInfo* windowInfo = windowHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003169 ui::LogicalDisplayId displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003170 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003171 TouchOcclusionInfo info;
3172 info.hasBlockingOcclusion = false;
3173 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003174 info.obscuringUid = gui::Uid::INVALID;
3175 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003176 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003177 if (windowHandle == otherHandle) {
3178 break; // All future windows are below us. Exit early.
3179 }
chaviw98318de2021-05-19 16:45:23 -05003180 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li5e5645e2024-03-05 14:43:05 +00003181 if (canBeObscuredBy(windowHandle, otherHandle) &&
3182 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId)) &&
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003183 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003184 if (DEBUG_TOUCH_OCCLUSION) {
3185 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003186 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003187 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003188 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3189 // we perform the checks below to see if the touch can be propagated or not based on the
3190 // window's touch occlusion mode
3191 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3192 info.hasBlockingOcclusion = true;
3193 info.obscuringUid = otherInfo->ownerUid;
3194 info.obscuringPackage = otherInfo->packageName;
3195 break;
3196 }
3197 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003198 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003199 float opacity =
3200 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3201 // Given windows A and B:
3202 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3203 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3204 opacityByUid[uid] = opacity;
3205 if (opacity > info.obscuringOpacity) {
3206 info.obscuringOpacity = opacity;
3207 info.obscuringUid = uid;
3208 info.obscuringPackage = otherInfo->packageName;
3209 }
3210 }
3211 }
3212 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003213 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003214 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003215 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003216 return info;
3217}
3218
chaviw98318de2021-05-19 16:45:23 -05003219std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003220 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003221 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003222 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3223 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3224 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003225 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003226 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003227 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3228 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003229 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3230 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3231 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003232 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003233}
3234
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003235bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3236 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003237 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3238 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003239 return false;
3240 }
3241 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003242 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003243 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003244 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003245 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3246 return false;
3247 }
3248 return true;
3249}
3250
chaviw98318de2021-05-19 16:45:23 -05003251bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Linnan Li5e5645e2024-03-05 14:43:05 +00003252 float x, float y) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003253 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003254 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3255 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003256 if (windowHandle == otherHandle) {
3257 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
chaviw98318de2021-05-19 16:45:23 -05003259 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003260 if (canBeObscuredBy(windowHandle, otherHandle) &&
Linnan Li5e5645e2024-03-05 14:43:05 +00003261 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262 return true;
3263 }
3264 }
3265 return false;
3266}
3267
chaviw98318de2021-05-19 16:45:23 -05003268bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003269 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003270 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3271 const WindowInfo* windowInfo = windowHandle->getInfo();
3272 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003273 if (windowHandle == otherHandle) {
3274 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003275 }
chaviw98318de2021-05-19 16:45:23 -05003276 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003277 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003278 return true;
3279 }
3280 }
3281 return false;
3282}
3283
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003284std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003285 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003286 if (applicationHandle != nullptr) {
3287 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003288 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 } else {
3290 return applicationHandle->getName();
3291 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003292 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003293 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003295 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297}
3298
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003299void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003300 if (!isUserActivityEvent(eventEntry)) {
3301 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003302 return;
3303 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003304
3305 const int32_t eventType = getUserActivityEventType(eventEntry);
3306 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3307 // Note that we're directly getting the time diff between the current event and the previous
3308 // event. This is assuming that the first user event always happens at a timestamp that is
3309 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3310 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3311 // value than the potential first user activity event time, so this is ok.
3312 std::chrono::nanoseconds timeSinceLastEvent =
3313 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3314 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3315 return;
3316 }
3317 }
3318
Linnan Li13bf76a2024-05-05 19:18:02 +08003319 ui::LogicalDisplayId displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003320 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003321 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003322 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003323 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003324 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003325 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 }
3327 }
3328
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003329 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003330 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003331 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3332 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 return;
3334 }
Josep del Riob3981622023-04-18 15:49:45 +00003335 if (windowDisablingUserActivityInfo != nullptr) {
3336 if (DEBUG_DISPATCH_CYCLE) {
3337 ALOGD("Not poking user activity: disabled by window '%s'.",
3338 windowDisablingUserActivityInfo->name.c_str());
3339 }
3340 return;
3341 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003344 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003345 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3346 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 return;
3348 }
Josep del Riob3981622023-04-18 15:49:45 +00003349 // Don't inhibit events that were intercepted or are not passed to
3350 // the apps, like system shortcuts
3351 if (windowDisablingUserActivityInfo != nullptr &&
Josep del Rioc8fdedb2024-05-21 13:32:43 +00003352 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP) {
Josep del Riob3981622023-04-18 15:49:45 +00003353 if (DEBUG_DISPATCH_CYCLE) {
3354 ALOGD("Not poking user activity: disabled by window '%s'.",
3355 windowDisablingUserActivityInfo->name.c_str());
3356 }
3357 return;
3358 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003361 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003362 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003363 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003364 break;
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
3367
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003368 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003369 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3370 REQUIRES(mLock) {
3371 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003372 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003373 };
3374 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375}
3376
3377void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003378 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003379 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003380 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003381 ATRACE_NAME_IF(ATRACE_ENABLED(),
3382 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3383 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003384 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003385 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003386 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003387 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003388 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003389 inputTarget.getPointerInfoString().c_str());
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
3392 // Skip this event if the connection status is not normal.
3393 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003394 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003395 if (DEBUG_DISPATCH_CYCLE) {
3396 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003397 connection->getInputChannelName().c_str(),
3398 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 return;
3401 }
3402
3403 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003404 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003405 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003406 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003407 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003409 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003410 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003411 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3412 logDispatchStateLocked();
3413 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3414 "target on connection "
3415 << connection->getInputChannelName() << " for "
3416 << originalMotionEntry.getDescription();
3417 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003418 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003419 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003420 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 if (!splitMotionEntry) {
3422 return; // split event was dropped
3423 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003424 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3425 std::string reason = std::string("reason=pointer cancel on split window");
3426 android_log_event_list(LOGTAG_INPUT_CANCEL)
3427 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3428 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003429 if (DEBUG_FOCUS) {
3430 ALOGD("channel '%s' ~ Split motion event.",
3431 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003432 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003433 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003434 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3435 std::move(splitMotionEntry),
3436 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 return;
3438 }
3439 }
3440
3441 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003442 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3443 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444}
3445
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003446void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3447 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3448 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003449 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003450 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3451 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003452 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003453
hongzuo liu95785e22022-09-06 02:51:35 +00003454 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003456 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
3458 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003459 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 startDispatchCycleLocked(currentTime, connection);
3461 }
3462}
3463
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003464void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003465 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003466 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003467 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3468 eventEntry->type == EventEntry::Type::MOTION;
3469 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3470 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3471 << inputTarget << " connection: " << connection->getInputChannelName()
3472 << " entry: " << eventEntry->getDescription();
3473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 // This is a new event.
3475 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003476 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003477 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
Prabir Pradhana67623c2024-02-21 06:57:36 +00003478 mWindowInfosVsyncId, mTracer.get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003480 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3481 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003482 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003484 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003485 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003486 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3487 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003488 LOG(WARNING) << "channel " << connection->getInputChannelName()
3489 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 return; // skip the inconsistent event
3491 }
3492 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003495 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003496 std::shared_ptr<const MotionEntry> resolvedMotion =
3497 std::static_pointer_cast<const MotionEntry>(eventEntry);
3498 {
3499 // Determine the resolved motion entry.
3500 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3501 int32_t resolvedAction = motionEntry.action;
3502 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003504 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003505 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003506 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003507 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003508 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003509 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003510 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003511 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003512 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003513 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3514 }
3515 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3516 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3517 motionEntry.displayId)) {
3518 if (DEBUG_DISPATCH_CYCLE) {
3519 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3520 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3521 "enter event";
3522 }
3523 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3524 }
3525
3526 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3527 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3528 }
3529 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3530 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3531 }
3532 if (dispatchEntry->targetFlags.test(
3533 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3534 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3535 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003536 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3537 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3538 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003539
3540 dispatchEntry->resolvedFlags = resolvedFlags;
3541 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003542 std::optional<std::vector<PointerProperties>> usingProperties;
3543 std::optional<std::vector<PointerCoords>> usingCoords;
3544 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3545 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3546 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3547 // the dispatcher, and therefore the coordinates of this event are currently
3548 // incorrect. These events should use the coordinates of the last dispatched
3549 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3550 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3551 std::optional<std::pair<std::vector<PointerProperties>,
3552 std::vector<PointerCoords>>>
3553 pointerInfo =
3554 connection->inputState.getPointersOfLastEvent(motionEntry,
3555 hovering);
3556 if (pointerInfo) {
3557 usingProperties = pointerInfo->first;
3558 usingCoords = pointerInfo->second;
3559 }
3560 }
Prabir Pradhana67623c2024-02-21 06:57:36 +00003561 {
3562 // Generate a new MotionEntry with a new eventId using the resolved action
3563 // and flags, and set it as the resolved entry.
3564 auto newEntry = std::make_shared<
3565 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3566 motionEntry.eventTime, motionEntry.deviceId,
3567 motionEntry.source, motionEntry.displayId,
3568 motionEntry.policyFlags, resolvedAction,
3569 motionEntry.actionButton, resolvedFlags,
3570 motionEntry.metaState, motionEntry.buttonState,
3571 motionEntry.classification, motionEntry.edgeFlags,
3572 motionEntry.xPrecision, motionEntry.yPrecision,
3573 motionEntry.xCursorPosition,
3574 motionEntry.yCursorPosition, motionEntry.downTime,
3575 usingProperties.value_or(
3576 motionEntry.pointerProperties),
3577 usingCoords.value_or(motionEntry.pointerCoords));
3578 if (mTracer) {
3579 ensureEventTraced(motionEntry);
3580 newEntry->traceTracker =
3581 mTracer->traceDerivedEvent(*newEntry,
3582 *motionEntry.traceTracker);
3583 }
3584 resolvedMotion = newEntry;
3585 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003586 if (ATRACE_ENABLED()) {
3587 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3588 ") to MotionEvent(id=0x%" PRIx32 ").",
3589 motionEntry.id, resolvedMotion->id);
3590 ATRACE_NAME(message.c_str());
3591 }
3592
3593 // Set the resolved motion entry in the DispatchEntry.
3594 dispatchEntry->eventEntry = resolvedMotion;
3595 eventEntry = resolvedMotion;
3596 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003599 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3600 // devices being active at the same time in the same window, so if a new device is
3601 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003602 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003603 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003604 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003605 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003606 << connection->getInputChannelName() << " with event "
3607 << cancelEvent->getDescription();
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003608 if (mTracer) {
3609 static_cast<MotionEntry&>(*cancelEvent).traceTracker =
3610 mTracer->traceDerivedEvent(*cancelEvent, *resolvedMotion->traceTracker);
3611 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003612 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003613 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhana67623c2024-02-21 06:57:36 +00003614 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId,
3615 mTracer.get());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003616
3617 // Send these cancel events to the queue before sending the event from the new
3618 // device.
3619 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3620 }
3621
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003622 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003624 LOG(WARNING) << "channel " << connection->getInputChannelName()
3625 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626 return; // skip the inconsistent event
3627 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003628 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003629 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003630 // Skip reporting pointer down outside focus to the policy.
3631 break;
3632 }
3633
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003634 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003635 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003636
3637 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003639 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003640 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003641 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3642 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003643 break;
3644 }
Chris Yef59a2f42020-10-16 12:55:26 -07003645 case EventEntry::Type::SENSOR: {
3646 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3647 break;
3648 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003649 case EventEntry::Type::DEVICE_RESET: {
3650 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003651 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003652 break;
3653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
3655
3656 // Remember that we are waiting for this dispatch to complete.
3657 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003658 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660
3661 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003662 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003663 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003664}
3665
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003666/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003667 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003668 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003669 * The first role is to log input interaction with windows, which helps determine what the user was
3670 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3671 * that user started interacting with launcher window, as well as any other window that received
3672 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3673 * when the set of tokens that received the event changes. It is not logged again as long as the
3674 * user is interacting with the same windows.
3675 *
3676 * The second role is to track input device activity for metrics collection. For each input event,
3677 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3678 * input_interaction logs, the device interaction is reported even when the set of interaction
3679 * tokens do not change.
3680 *
3681 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3682 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003683 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003684void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3685 const std::vector<InputTarget>& targets) {
3686 int32_t deviceId;
3687 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003688 // Skip ACTION_UP events, and all events other than keys and motions
3689 if (entry.type == EventEntry::Type::KEY) {
3690 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3691 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3692 return;
3693 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003694 deviceId = keyEntry.deviceId;
3695 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003696 } else if (entry.type == EventEntry::Type::MOTION) {
3697 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3698 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003699 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3700 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003701 return;
3702 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003703 deviceId = motionEntry.deviceId;
3704 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003705 } else {
3706 return; // Not a key or a motion
3707 }
3708
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003709 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003710 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003711 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003712 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003713 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003714 continue; // Skip windows that receive ACTION_OUTSIDE
3715 }
3716
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003717 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003718 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003719 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003720 if (target.windowHandle) {
3721 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3722 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003723 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003724
3725 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3726 REQUIRES(mLock) {
3727 scoped_unlock unlock(mLock);
3728 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3729 };
3730 postCommandLocked(std::move(command));
3731
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003732 if (newConnectionTokens == mInteractionConnectionTokens) {
3733 return; // no change
3734 }
3735 mInteractionConnectionTokens = newConnectionTokens;
3736
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003737 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003738 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003739 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003740 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003741 std::string message = "Interaction with: " + targetList;
3742 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003743 message += "<none>";
3744 }
3745 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3746}
3747
chaviwfd6d3512019-03-25 13:23:49 -07003748void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003749 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003750 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003751 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3752 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003753 return;
3754 }
3755
Vishnu Nairc519ff72021-01-21 08:23:08 -08003756 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003757 if (focusedToken == token) {
3758 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003759 return;
3760 }
3761
Prabir Pradhancef936d2021-07-21 16:17:52 +00003762 auto command = [this, token]() REQUIRES(mLock) {
3763 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003764 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003765 };
3766 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767}
3768
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003769status_t InputDispatcher::publishMotionEvent(Connection& connection,
3770 DispatchEntry& dispatchEntry) const {
3771 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3772 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3773
3774 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003775 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003776
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003777 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003778 // Set the X and Y offset and X and Y scale depending on the input source.
3779 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003780 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003781 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3782 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003783 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003784 scaledCoords[i] = motionEntry.pointerCoords[i];
3785 // Don't apply window scale here since we don't want scale to affect raw
3786 // coordinates. The scale will be sent back to the client and applied
3787 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003788 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003789 }
3790 usingCoords = scaledCoords;
3791 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003792 }
3793
3794 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3795
3796 // Publish the motion event.
3797 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003798 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3799 motionEntry.source, motionEntry.displayId, std::move(hmac),
3800 motionEntry.action, motionEntry.actionButton,
3801 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3802 motionEntry.metaState, motionEntry.buttonState,
3803 motionEntry.classification, dispatchEntry.transform,
3804 motionEntry.xPrecision, motionEntry.yPrecision,
3805 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3806 dispatchEntry.rawTransform, motionEntry.downTime,
3807 motionEntry.eventTime, motionEntry.getPointerCount(),
3808 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003809}
3810
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003812 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003813 ATRACE_NAME_IF(ATRACE_ENABLED(),
3814 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3815 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003816 if (DEBUG_DISPATCH_CYCLE) {
3817 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003820 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003821 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003823 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003824 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825
3826 // Publish the event.
3827 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003828 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3829 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003830 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003831 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3832 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003833 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003834 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3835 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003838 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003839 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003840 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3841 keyEntry.deviceId, keyEntry.source,
3842 keyEntry.displayId, std::move(hmac),
3843 keyEntry.action, dispatchEntry->resolvedFlags,
3844 keyEntry.keyCode, keyEntry.scanCode,
3845 keyEntry.metaState, keyEntry.repeatCount,
3846 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003847 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003848 ensureEventTraced(keyEntry);
3849 mTracer->traceEventDispatch(*dispatchEntry, *keyEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003850 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 }
3853
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003854 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003855 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003856 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3857 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003858 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003859 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003860 status = publishMotionEvent(*connection, *dispatchEntry);
Siarhei Vishniakoub0058742024-07-01 16:42:49 -07003861 if (status == BAD_VALUE) {
3862 logDispatchStateLocked();
3863 LOG(FATAL) << "Publisher failed for " << motionEntry;
3864 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003865 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003866 ensureEventTraced(motionEntry);
3867 mTracer->traceEventDispatch(*dispatchEntry, *motionEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003868 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 break;
3870 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003871
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003872 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003873 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003874 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003875 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003876 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003877 break;
3878 }
3879
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003880 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3881 const TouchModeEntry& touchModeEntry =
3882 static_cast<const TouchModeEntry&>(eventEntry);
3883 status = connection->inputPublisher
3884 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3885 touchModeEntry.inTouchMode);
3886
3887 break;
3888 }
3889
Prabir Pradhan99987712020-11-10 18:43:05 -08003890 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3891 const auto& captureEntry =
3892 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
Hiroki Sato25040232024-02-22 17:21:22 +09003893 status =
3894 connection->inputPublisher
3895 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3896 captureEntry.pointerCaptureRequest.isEnable());
Prabir Pradhan99987712020-11-10 18:43:05 -08003897 break;
3898 }
3899
arthurhungb89ccb02020-12-30 16:19:01 +08003900 case EventEntry::Type::DRAG: {
3901 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3902 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3903 dragEntry.id, dragEntry.x,
3904 dragEntry.y,
3905 dragEntry.isExiting);
3906 break;
3907 }
3908
Chris Yef59a2f42020-10-16 12:55:26 -07003909 case EventEntry::Type::DEVICE_RESET:
3910 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003911 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003912 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916
3917 // Check the result.
3918 if (status) {
3919 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003920 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003922 "This is unexpected because the wait queue is empty, so the pipe "
3923 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003924 "event to it, status=%s(%d)",
3925 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3926 status);
Harry Cutts33476232023-01-30 19:57:29 +00003927 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 } else {
3929 // Pipe is full and we are waiting for the app to finish process some events
3930 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003931 if (DEBUG_DISPATCH_CYCLE) {
3932 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3933 "waiting for the application to catch up",
3934 connection->getInputChannelName().c_str());
3935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
3937 } else {
3938 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003939 "status=%s(%d)",
3940 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3941 status);
Harry Cutts33476232023-01-30 19:57:29 +00003942 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944 return;
3945 }
3946
3947 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003948 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3949 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3950 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003951 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003952 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003953 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003954 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003955 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
3957}
3958
chaviw09c8d2d2020-08-24 15:48:26 -07003959std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3960 size_t size;
3961 switch (event.type) {
3962 case VerifiedInputEvent::Type::KEY: {
3963 size = sizeof(VerifiedKeyEvent);
3964 break;
3965 }
3966 case VerifiedInputEvent::Type::MOTION: {
3967 size = sizeof(VerifiedMotionEvent);
3968 break;
3969 }
3970 }
3971 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3972 return mHmacKeyManager.sign(start, size);
3973}
3974
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003975const std::array<uint8_t, 32> InputDispatcher::getSignature(
3976 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003977 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003978 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003979 // Only sign events up and down events as the purely move events
3980 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003981 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003982 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003983
3984 VerifiedMotionEvent verifiedEvent =
3985 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3986 verifiedEvent.actionMasked = actionMasked;
3987 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3988 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003989}
3990
3991const std::array<uint8_t, 32> InputDispatcher::getSignature(
3992 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3993 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3994 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003995 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003996}
3997
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003999 const std::shared_ptr<Connection>& connection,
4000 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004001 if (DEBUG_DISPATCH_CYCLE) {
4002 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
4003 connection->getInputChannelName().c_str(), seq, toString(handled));
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004006 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 return;
4008 }
4009
4010 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00004011 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
4012 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
4013 };
4014 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015}
4016
4017void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004018 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004019 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004020 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004021 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
4022 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024
4025 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004026 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00004027 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004028 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00004029 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
4031 // The connection appears to be unrecoverably broken.
4032 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004033 if (connection->status == Connection::Status::NORMAL) {
4034 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
4036 if (notify) {
4037 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00004038 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
4039 connection->getInputChannelName().c_str());
4040
4041 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004042 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004043 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00004044 };
4045 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
4047 }
4048}
4049
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004050void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004051 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004052 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004053 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
4055}
4056
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004057void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004059 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061}
4062
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004063int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
4064 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004065 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004066 if (connection == nullptr) {
4067 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
4068 connectionToken.get(), events);
4069 return 0; // remove the callback
4070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004072 bool notify;
4073 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
4074 if (!(events & ALOOPER_EVENT_INPUT)) {
4075 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
4076 "events=0x%x",
4077 connection->getInputChannelName().c_str(), events);
4078 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 }
4080
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004081 nsecs_t currentTime = now();
4082 bool gotOne = false;
4083 status_t status = OK;
4084 for (;;) {
4085 Result<InputPublisher::ConsumerResponse> result =
4086 connection->inputPublisher.receiveConsumerResponse();
4087 if (!result.ok()) {
4088 status = result.error().code();
4089 break;
4090 }
4091
4092 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
4093 const InputPublisher::Finished& finish =
4094 std::get<InputPublisher::Finished>(*result);
4095 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
4096 finish.consumeTime);
4097 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004098 if (shouldReportMetricsForConnection(*connection)) {
4099 const InputPublisher::Timeline& timeline =
4100 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004101 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
4102 connection->getToken(),
4103 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004104 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004105 }
4106 gotOne = true;
4107 }
4108 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004109 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004110 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 return 1;
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
4114
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004115 notify = status != DEAD_OBJECT || !connection->monitor;
4116 if (notify) {
4117 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4118 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4119 status);
4120 }
4121 } else {
4122 // Monitor channels are never explicitly unregistered.
4123 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004124 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004125 notify = !connection->monitor && stillHaveWindowHandle;
4126 if (notify) {
4127 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4128 connection->getInputChannelName().c_str(), events);
4129 }
4130 }
4131
4132 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004133 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004134 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135}
4136
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004139 // Cancel windows (i.e. non-monitors).
4140 // A channel must have at least one window to receive any input. If a window was removed, the
4141 // event streams directed to the window will already have been canceled during window removal.
4142 // So there is no need to generate cancellations for connections without any windows.
4143 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4144 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4145 // through a non-touched window if there are more than one window for an input channel.
4146 if (cancelPointers) {
4147 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4148 if (options.displayId.has_value() && options.displayId != displayId) {
4149 continue;
4150 }
4151 for (const auto& touchedWindow : touchState.windows) {
4152 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4153 }
4154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004156 // Follow up by generating cancellations for all windows, because we don't explicitly track
4157 // the windows that have an ongoing focus event stream.
4158 if (cancelNonPointers) {
4159 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4160 for (const auto& windowHandle : handles) {
4161 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4162 }
4163 }
4164 }
4165
4166 // Cancel monitors.
4167 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168}
4169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004171 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004172 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004173 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004174 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4175 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004176 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004177 }
4178}
4179
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004180void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4181 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4182 const std::shared_ptr<Connection>& connection) {
4183 if (windowHandle == nullptr) {
4184 LOG(FATAL) << __func__ << ": Window handle must not be null";
4185 }
4186 if (connection) {
4187 // The connection can be optionally provided to avoid multiple lookups.
4188 if (windowHandle->getToken() != connection->getToken()) {
4189 LOG(FATAL) << __func__
4190 << ": Wrong connection provided for window: " << windowHandle->getName();
4191 }
4192 }
4193
4194 std::shared_ptr<Connection> resolvedConnection =
4195 connection ? connection : getConnectionLocked(windowHandle->getToken());
4196 if (!resolvedConnection) {
4197 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4198 return;
4199 }
4200 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4201}
4202
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004204 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4205 const sp<WindowInfoHandle>& window) {
4206 if (!connection->monitor && window == nullptr) {
4207 LOG(FATAL) << __func__
4208 << ": Cannot send event to non-monitor channel without a window - channel: "
4209 << connection->getInputChannelName();
4210 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004211 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 return;
4213 }
4214
4215 nsecs_t currentTime = now();
4216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004218 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004220 if (cancelationEvents.empty()) {
4221 return;
4222 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004223
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004224 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4225 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004226 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004227 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004228 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004229 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004230
Arthur Hungb3307ee2021-10-14 10:57:37 +00004231 std::string reason = std::string("reason=").append(options.reason);
4232 android_log_event_list(LOGTAG_INPUT_CANCEL)
4233 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4234
hongzuo liu95785e22022-09-06 02:51:35 +00004235 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004236 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004237 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004238 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004239
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004240 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004241 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004242 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004243
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004244 switch (cancelationEventEntry->type) {
4245 case EventEntry::Type::KEY: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004246 if (mTracer) {
4247 static_cast<KeyEntry&>(*cancelationEventEntry).traceTracker =
4248 mTracer->traceDerivedEvent(*cancelationEventEntry,
4249 *options.traceTracker);
4250 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004251 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004252 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004253 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4254 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004255 } else {
4256 targets.emplace_back(fallbackTarget);
4257 }
4258 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004261 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004262 if (mTracer) {
4263 static_cast<MotionEntry&>(*cancelationEventEntry).traceTracker =
4264 mTracer->traceDerivedEvent(*cancelationEventEntry,
4265 *options.traceTracker);
4266 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004267 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004268 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004269 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004270 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004271 pointerIndex++) {
4272 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4273 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004274 if (mDragState && mDragState->dragWindow->getToken() == token &&
4275 pointerIds.test(mDragState->pointerId)) {
4276 LOG(INFO) << __func__
4277 << ": Canceling drag and drop because the pointers for the drag "
4278 "window are being canceled.";
4279 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4280 mDragState.reset();
4281 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004282 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4283 ftl::Flags<InputTarget::Flags>(), pointerIds,
4284 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004285 } else {
4286 targets.emplace_back(fallbackTarget);
4287 const auto it = mDisplayInfos.find(motionEntry.displayId);
4288 if (it != mDisplayInfos.end()) {
4289 targets.back().displayTransform = it->second.transform;
4290 targets.back().setDefaultPointerTransform(it->second.transform);
4291 }
4292 }
4293 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004294 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004296 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004297 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004298 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4299 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004300 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004301 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004302 break;
4303 }
Chris Yef59a2f42020-10-16 12:55:26 -07004304 case EventEntry::Type::DEVICE_RESET:
4305 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004306 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004307 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004308 break;
4309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004312 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004313 if (mTracer) {
4314 mTracer->dispatchToTargetHint(*options.traceTracker, targets[0]);
4315 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004316 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004318
hongzuo liu95785e22022-09-06 02:51:35 +00004319 // If the outbound queue was previously empty, start the dispatch cycle going.
4320 if (wasEmpty && !connection->outboundQueue.empty()) {
4321 startDispatchCycleLocked(currentTime, connection);
4322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323}
4324
Svet Ganov5d3bc372020-01-26 23:11:07 -08004325void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004326 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004327 ftl::Flags<InputTarget::Flags> targetFlags,
4328 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004329 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004330 return;
4331 }
4332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004333 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004334 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004335
4336 if (downEvents.empty()) {
4337 return;
4338 }
4339
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004340 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004341 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4342 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004343 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004344
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004345 const auto [_, touchedWindowState, displayId] =
4346 findTouchStateWindowAndDisplayLocked(connection->getToken());
4347 if (touchedWindowState == nullptr) {
4348 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4349 }
4350 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004351
hongzuo liu95785e22022-09-06 02:51:35 +00004352 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004354 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004355 switch (downEventEntry->type) {
4356 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004357 if (mTracer) {
4358 static_cast<MotionEntry&>(*downEventEntry).traceTracker =
4359 mTracer->traceDerivedEvent(*downEventEntry, *traceTracker);
4360 }
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004361 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4362 if (windowHandle != nullptr) {
4363 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004364 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004365 pointerIndex++) {
4366 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4367 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004368 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4369 targetFlags, pointerIds, motionEntry.downTime,
4370 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004371 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004372 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004373 const auto it = mDisplayInfos.find(motionEntry.displayId);
4374 if (it != mDisplayInfos.end()) {
4375 targets.back().displayTransform = it->second.transform;
4376 targets.back().setDefaultPointerTransform(it->second.transform);
4377 }
4378 }
4379 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004380 break;
4381 }
4382
4383 case EventEntry::Type::KEY:
4384 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004385 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004386 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004387 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004388 case EventEntry::Type::SENSOR:
4389 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004390 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004391 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004392 break;
4393 }
4394 }
4395
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004396 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004397 if (mTracer) {
4398 mTracer->dispatchToTargetHint(*traceTracker, targets[0]);
4399 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004400 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004401 }
4402
hongzuo liu95785e22022-09-06 02:51:35 +00004403 // If the outbound queue was previously empty, start the dispatch cycle going.
4404 if (wasEmpty && !connection->outboundQueue.empty()) {
4405 startDispatchCycleLocked(downTime, connection);
4406 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004407}
4408
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004409std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004410 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4411 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004412 const auto& [action, pointerProperties, pointerCoords] =
4413 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4414 /*historySize=*/0, originalMotionEntry.pointerProperties,
4415 originalMotionEntry.pointerCoords, pointerIds);
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004416 if (pointerIds.count() != pointerCoords.size()) {
4417 // TODO(b/329107108): Determine why some IDs in pointerIds were not in originalMotionEntry.
4418 // This is bad. We are missing some of the pointers that we expected to deliver.
4419 // Most likely this indicates that we received an ACTION_MOVE events that has
4420 // different pointer ids than we expected based on the previous ACTION_DOWN
4421 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4422 // in this way.
Siarhei Vishniakoued89cbb2023-10-13 10:42:44 -07004423 ALOGW("Dropping split motion event because the pointer count is %zu but "
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004424 "we expected there to be %zu pointers. This probably means we received "
4425 "a broken sequence of pointer ids from the input device: %s",
4426 pointerCoords.size(), pointerIds.count(),
4427 originalMotionEntry.getDescription().c_str());
4428 return nullptr;
4429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004431 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4432 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004433 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4434 logDispatchStateLocked();
4435 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4436 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4437 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004438 }
4439
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004440 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004441 ATRACE_NAME_IF(ATRACE_ENABLED(),
4442 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4443 ").",
4444 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004445 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004446 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4447 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004448 originalMotionEntry.deviceId, originalMotionEntry.source,
4449 originalMotionEntry.displayId,
4450 originalMotionEntry.policyFlags, action,
4451 originalMotionEntry.actionButton,
4452 originalMotionEntry.flags, originalMotionEntry.metaState,
4453 originalMotionEntry.buttonState,
4454 originalMotionEntry.classification,
4455 originalMotionEntry.edgeFlags,
4456 originalMotionEntry.xPrecision,
4457 originalMotionEntry.yPrecision,
4458 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004459 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004460 pointerProperties, pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +00004461 if (mTracer) {
4462 splitMotionEntry->traceTracker =
4463 mTracer->traceDerivedEvent(*splitMotionEntry, *originalMotionEntry.traceTracker);
4464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 return splitMotionEntry;
4467}
4468
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004469void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4470 std::scoped_lock _l(mLock);
Liana Kazanova5b8217b2024-07-18 17:44:51 +00004471 // Reset key repeating in case a keyboard device was added or removed or something.
4472 resetKeyRepeatLocked();
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004473 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4474}
4475
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004476void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004477 ALOGD_IF(debugInboundEventDetails(),
4478 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
Linnan Li13bf76a2024-05-05 19:18:02 +08004479 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, action=%s, flags=0x%x, "
4480 "keyCode=%s, scanCode=0x%x, metaState=0x%x, "
Prabir Pradhan96282b02023-02-24 22:36:17 +00004481 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004482 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004483 args.displayId.toString().c_str(), args.policyFlags,
4484 KeyEvent::actionToString(args.action), args.flags, KeyEvent::getLabel(args.keyCode),
4485 args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004486 Result<void> keyCheck = validateKeyEvent(args.action);
4487 if (!keyCheck.ok()) {
4488 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 return;
4490 }
4491
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492 uint32_t policyFlags = args.policyFlags;
4493 int32_t flags = args.flags;
4494 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004495 // InputDispatcher tracks and generates key repeats on behalf of
4496 // whatever notifies it, so repeatCount should always be set to 0
4497 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4499 policyFlags |= POLICY_FLAG_VIRTUAL;
4500 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 if (policyFlags & POLICY_FLAG_FUNCTION) {
4503 metaState |= AMETA_FUNCTION_ON;
4504 }
4505
4506 policyFlags |= POLICY_FLAG_TRUSTED;
4507
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004508 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004510 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4511 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4512 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513
Michael Wright2b3c3302018-03-02 17:19:13 +00004514 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004515 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004516 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4517 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004518 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520
Antonio Kantekf16f2832021-09-28 04:39:20 +00004521 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 { // acquire lock
4523 mLock.lock();
4524
Asmita Poddar2808d7e2024-09-12 13:15:38 +00004525 if (input_flags::keyboard_repeat_keys() && !mConfig.keyRepeatEnabled) {
4526 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
4527 }
4528
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 if (shouldSendKeyToInputFilterLocked(args)) {
4530 mLock.unlock();
4531
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004532 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004533 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 return; // event was consumed by the filter
4535 }
4536
4537 mLock.lock();
4538 }
4539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004540 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004541 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4542 args.deviceId, args.source, args.displayId, policyFlags,
4543 args.action, flags, keyCode, args.scanCode, metaState,
4544 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004545 if (mTracer) {
4546 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
Asmita Poddar92135902024-09-30 16:10:59 +00004549 if (mPerDeviceInputLatencyMetricsFlag) {
jioana099e19a2024-09-19 15:37:34 +00004550 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4551 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
4552 !mInputFilterEnabled) {
4553 mLatencyTracker.trackNotifyKey(args);
4554 }
4555 }
4556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004557 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 mLock.unlock();
4559 } // release lock
4560
4561 if (needWake) {
4562 mLooper->wake();
4563 }
4564}
4565
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004566bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 return mInputFilterEnabled;
4568}
4569
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004570void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004571 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004572 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08004573 "displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004574 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004575 "xCursorPosition=%f, yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004577 args.displayId.toString().c_str(), args.policyFlags,
4578 MotionEvent::actionToString(args.action).c_str(), args.actionButton, args.flags,
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004579 args.metaState, args.buttonState, args.xCursorPosition, args.yCursorPosition,
4580 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004581 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004582 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4583 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004584 i, args.pointerProperties[i].id,
4585 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4586 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4587 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4588 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4589 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4590 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4591 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4592 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4593 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4594 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004597
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004598 Result<void> motionCheck =
4599 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4600 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004601 if (!motionCheck.ok()) {
4602 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4603 return;
4604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004606 if (DEBUG_VERIFY_EVENTS) {
4607 auto [it, _] =
4608 mVerifiersByDisplay.try_emplace(args.displayId,
Linnan Li13bf76a2024-05-05 19:18:02 +08004609 StringPrintf("display %s",
4610 args.displayId.toString().c_str()));
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004611 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004612 it->second.processMovement(args.deviceId, args.source, args.action,
4613 args.getPointerCount(), args.pointerProperties.data(),
4614 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004615 if (!result.ok()) {
4616 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4617 }
4618 }
4619
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004620 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004622
4623 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004624 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4625 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004626 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4627 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630
Antonio Kantekf16f2832021-09-28 04:39:20 +00004631 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 { // acquire lock
4633 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004634 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4635 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4636 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004637 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004638 if (touchStateIt != mTouchStatesByDisplay.end()) {
4639 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004640 if (touchState.hasTouchingPointers(args.deviceId) ||
4641 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004642 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4643 }
4644 }
4645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646
4647 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004648 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004649 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004650 displayTransform = it->second.transform;
4651 }
4652
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 mLock.unlock();
4654
4655 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4657 args.action, args.actionButton, args.flags, args.edgeFlags,
4658 args.metaState, args.buttonState, args.classification,
4659 displayTransform, args.xPrecision, args.yPrecision,
4660 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004661 args.downTime, args.eventTime, args.getPointerCount(),
4662 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
4664 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004665 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 return; // event was consumed by the filter
4667 }
4668
4669 mLock.lock();
4670 }
4671
4672 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004673 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004674 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4675 args.deviceId, args.source, args.displayId,
4676 policyFlags, args.action, args.actionButton,
4677 args.flags, args.metaState, args.buttonState,
4678 args.classification, args.edgeFlags, args.xPrecision,
4679 args.yPrecision, args.xCursorPosition,
4680 args.yCursorPosition, args.downTime,
4681 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004682 if (mTracer) {
4683 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004686 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4687 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004688 !mInputFilterEnabled) {
jioana099e19a2024-09-19 15:37:34 +00004689 mLatencyTracker.trackNotifyMotion(args);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004690 }
4691
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004692 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 mLock.unlock();
4694 } // release lock
4695
4696 if (needWake) {
4697 mLooper->wake();
4698 }
4699}
4700
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004701void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004702 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004703 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4704 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004705 args.id, args.eventTime, args.deviceId, args.source,
4706 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004707 }
Chris Yef59a2f42020-10-16 12:55:26 -07004708
Antonio Kantekf16f2832021-09-28 04:39:20 +00004709 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004710 { // acquire lock
4711 mLock.lock();
4712
4713 // Just enqueue a new sensor event.
4714 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004715 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4716 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4717 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004718
4719 needWake = enqueueInboundEventLocked(std::move(newEntry));
4720 mLock.unlock();
4721 } // release lock
4722
4723 if (needWake) {
4724 mLooper->wake();
4725 }
4726}
4727
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004728void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004729 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004730 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4731 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004732 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004733 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004734}
4735
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004736bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004737 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738}
4739
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004740void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004741 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004742 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4743 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004744 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004747 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004749 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750}
4751
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004752void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004753 // TODO(b/308677868) Remove device reset from the InputListener interface
Prabir Pradhan65613802023-02-22 23:36:58 +00004754 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004755 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4756 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
Antonio Kantekf16f2832021-09-28 04:39:20 +00004759 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004761 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004763 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004764 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004765 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004766
4767 for (auto& [_, verifier] : mVerifiersByDisplay) {
4768 verifier.resetDevice(args.deviceId);
4769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 } // release lock
4771
4772 if (needWake) {
4773 mLooper->wake();
4774 }
4775}
4776
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004777void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004778 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004779 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
Hiroki Sato25040232024-02-22 17:21:22 +09004780 args.request.isEnable() ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004781 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004782
Antonio Kantekf16f2832021-09-28 04:39:20 +00004783 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004784 { // acquire lock
4785 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004786 auto entry =
4787 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004788 needWake = enqueueInboundEventLocked(std::move(entry));
4789 } // release lock
4790
4791 if (needWake) {
4792 mLooper->wake();
4793 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004794}
4795
Prabir Pradhan5735a322022-04-11 17:23:34 +00004796InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004797 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004798 InputEventInjectionSync syncMode,
4799 std::chrono::milliseconds timeout,
4800 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004801 Result<void> eventValidation = validateInputEvent(*event);
4802 if (!eventValidation.ok()) {
4803 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4804 return InputEventInjectionResult::FAILED;
4805 }
4806
Prabir Pradhan65613802023-02-22 23:36:58 +00004807 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004808 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4809 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4810 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4811 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004812 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004813 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
Prabir Pradhan5735a322022-04-11 17:23:34 +00004815 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004817 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004818 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4819 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4820 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4821 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4822 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004823 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004824 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004825 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004826 }
4827
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004828 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4829 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4830
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004831 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004833 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004834 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004835 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004836 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004837 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4838 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4839 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004840 int32_t keyCode = incomingKey.getKeyCode();
4841 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004842 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004843 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004844 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4845 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4846 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004848 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4849 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004850 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004851
4852 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4853 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004854 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4856 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4857 std::to_string(t.duration().count()).c_str());
4858 }
4859 }
4860
4861 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004862 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004863 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4864 incomingKey.getEventTime(), resolvedDeviceId,
4865 incomingKey.getSource(), incomingKey.getDisplayId(),
4866 policyFlags, action, flags, keyCode,
4867 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004868 incomingKey.getRepeatCount(),
4869 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004870 if (mTracer) {
4871 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004873 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004877 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004878 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004879 const bool isPointerEvent =
4880 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4881 // If a pointer event has no displayId specified, inject it to the default display.
Linnan Li13bf76a2024-05-05 19:18:02 +08004882 const ui::LogicalDisplayId displayId =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004883 isPointerEvent && (event->getDisplayId() == ui::LogicalDisplayId::INVALID)
4884 ? ui::LogicalDisplayId::DEFAULT
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004885 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004886 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004887
4888 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004889 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004890 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004891 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4892 motionEvent.getAction(), eventTime,
4893 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004894 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4895 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4896 std::to_string(t.duration().count()).c_str());
4897 }
4898 }
4899
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004900 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4901 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4902 }
4903
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004904 mLock.lock();
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004905
Siarhei Vishniakoueb75bc82024-06-04 13:05:45 -07004906 {
4907 // Verify all injected streams, whether the injection is coming from apps or from
4908 // input filter. Print an error if the stream becomes inconsistent with this event.
4909 // An inconsistent injected event sent could cause a crash in the later stages of
4910 // dispatching pipeline.
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004911 auto [it, _] =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004912 mInputFilterVerifiersByDisplay.try_emplace(displayId,
4913 std::string("Injection on ") +
4914 displayId.toString());
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004915 InputVerifier& verifier = it->second;
4916
4917 Result<void> result =
4918 verifier.processMovement(resolvedDeviceId, motionEvent.getSource(),
4919 motionEvent.getAction(),
4920 motionEvent.getPointerCount(),
4921 motionEvent.getPointerProperties(),
4922 motionEvent.getSamplePointerCoords(), flags);
4923 if (!result.ok()) {
4924 logDispatchStateLocked();
4925 LOG(ERROR) << "Inconsistent event: " << motionEvent
4926 << ", reason: " << result.error();
Siarhei Vishniakou9d0d65e2024-08-02 12:10:05 -07004927 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4928 mLock.unlock();
4929 return InputEventInjectionResult::FAILED;
4930 }
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004931 }
4932 }
4933
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004934 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004935 const size_t pointerCount = motionEvent.getPointerCount();
4936 const std::vector<PointerProperties>
4937 pointerProperties(motionEvent.getPointerProperties(),
4938 motionEvent.getPointerProperties() + pointerCount);
4939
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004940 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004941 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004942 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4943 *sampleEventTimes, resolvedDeviceId,
4944 motionEvent.getSource(), displayId, policyFlags,
4945 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004946 motionEvent.getActionButton(), flags,
4947 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004948 motionEvent.getButtonState(),
4949 motionEvent.getClassification(),
4950 motionEvent.getEdgeFlags(),
4951 motionEvent.getXPrecision(),
4952 motionEvent.getYPrecision(),
4953 motionEvent.getRawXCursorPosition(),
4954 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004955 motionEvent.getDownTime(), pointerProperties,
4956 std::vector<PointerCoords>(samplePointerCoords,
4957 samplePointerCoords +
4958 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004959 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004960 if (mTracer) {
4961 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4962 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004963 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004964 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004965 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004966 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004967 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004968 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4969 resolvedDeviceId, motionEvent.getSource(), displayId,
4970 policyFlags, motionEvent.getAction(),
4971 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004972 motionEvent.getMetaState(), motionEvent.getButtonState(),
4973 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4974 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4975 motionEvent.getRawXCursorPosition(),
4976 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4977 pointerProperties,
4978 std::vector<PointerCoords>(samplePointerCoords,
4979 samplePointerCoords +
4980 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004981 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4982 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004983 if (mTracer) {
4984 nextInjectedEntry->traceTracker =
4985 mTracer->traceInboundEvent(*nextInjectedEntry);
4986 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004987 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004988 }
4989 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004992 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004993 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004994 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995 }
4996
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004998 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004999 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005000 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08005001 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005002 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005003 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 }
5005
5006 mLock.unlock();
5007
5008 if (needWake) {
5009 mLooper->wake();
5010 }
5011
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005012 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005014 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005016 if (syncMode == InputEventInjectionSync::NONE) {
5017 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 } else {
5019 for (;;) {
5020 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005021 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 break;
5023 }
5024
5025 nsecs_t remainingTimeout = endTime - now();
5026 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005027 if (DEBUG_INJECTION) {
5028 ALOGD("injectInputEvent - Timed out waiting for injection result "
5029 "to become available.");
5030 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005031 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032 break;
5033 }
5034
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005035 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005038 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
5039 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005041 if (DEBUG_INJECTION) {
5042 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
5043 injectionState->pendingForegroundDispatches);
5044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 nsecs_t remainingTimeout = endTime - now();
5046 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005047 if (DEBUG_INJECTION) {
5048 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
5049 "dispatches to finish.");
5050 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005051 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 break;
5053 }
5054
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005055 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 }
5057 }
5058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 } // release lock
5060
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005061 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005062 LOG(INFO) << "injectInputEvent - Finished with result "
5063 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
5066 return injectionResult;
5067}
5068
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005069std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05005070 std::array<uint8_t, 32> calculatedHmac;
5071 std::unique_ptr<VerifiedInputEvent> result;
5072 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005073 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05005074 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
5075 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
5076 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005077 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05005078 break;
5079 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005080 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05005081 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
5082 VerifiedMotionEvent verifiedMotionEvent =
5083 verifiedMotionEventFromMotionEvent(motionEvent);
5084 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005085 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05005086 break;
5087 }
5088 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08005089 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05005090 return nullptr;
5091 }
5092 }
5093 if (calculatedHmac == INVALID_HMAC) {
5094 return nullptr;
5095 }
tyiu1573a672023-02-21 22:38:32 +00005096 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05005097 return nullptr;
5098 }
5099 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005100}
5101
Prabir Pradhan24047542023-11-02 17:14:59 +00005102void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005104 if (!entry.injectionState) {
5105 // Not an injected event.
5106 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005108
5109 InjectionState& injectionState = *entry.injectionState;
5110 if (DEBUG_INJECTION) {
5111 LOG(INFO) << "Setting input event injection result to "
5112 << ftl::enum_string(injectionResult);
5113 }
5114
5115 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
5116 // Log the outcome since the injector did not wait for the injection result.
5117 switch (injectionResult) {
5118 case InputEventInjectionResult::SUCCEEDED:
5119 ALOGV("Asynchronous input event injection succeeded.");
5120 break;
5121 case InputEventInjectionResult::TARGET_MISMATCH:
5122 ALOGV("Asynchronous input event injection target mismatch.");
5123 break;
5124 case InputEventInjectionResult::FAILED:
5125 ALOGW("Asynchronous input event injection failed.");
5126 break;
5127 case InputEventInjectionResult::TIMED_OUT:
5128 ALOGW("Asynchronous input event injection timed out.");
5129 break;
5130 case InputEventInjectionResult::PENDING:
5131 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5132 break;
5133 }
5134 }
5135
5136 injectionState.injectionResult = injectionResult;
5137 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138}
5139
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005140void InputDispatcher::transformMotionEntryForInjectionLocked(
5141 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005142 // Input injection works in the logical display coordinate space, but the input pipeline works
5143 // display space, so we need to transform the injected events accordingly.
5144 const auto it = mDisplayInfos.find(entry.displayId);
5145 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005146 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005147
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005148 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5149 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5150 const vec2 cursor =
5151 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5152 {entry.xCursorPosition, entry.yCursorPosition});
5153 entry.xCursorPosition = cursor.x;
5154 entry.yCursorPosition = cursor.y;
5155 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005156 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005157 entry.pointerCoords[i] =
Prabir Pradhan9a53b552024-06-04 02:59:40 +00005158 MotionEvent::calculateTransformedCoords(entry.source, entry.flags,
5159 transformToDisplay, entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005160 }
5161}
5162
Prabir Pradhan24047542023-11-02 17:14:59 +00005163void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005164 if (entry.injectionState) {
5165 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167}
5168
Prabir Pradhan24047542023-11-02 17:14:59 +00005169void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005170 if (entry.injectionState) {
5171 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005173 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005174 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176 }
5177}
5178
chaviw98318de2021-05-19 16:45:23 -05005179const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005180 ui::LogicalDisplayId displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005181 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005182 auto it = mWindowHandlesByDisplay.find(displayId);
5183 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005184}
5185
chaviw98318de2021-05-19 16:45:23 -05005186sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005187 const sp<IBinder>& windowHandleToken, std::optional<ui::LogicalDisplayId> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005188 if (windowHandleToken == nullptr) {
5189 return nullptr;
5190 }
5191
Prabir Pradhan16463382023-10-12 23:03:19 +00005192 if (!displayId) {
5193 // Look through all displays.
Linnan Li13bf76a2024-05-05 19:18:02 +08005194 for (const auto& [_, windowHandles] : mWindowHandlesByDisplay) {
Prabir Pradhan16463382023-10-12 23:03:19 +00005195 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5196 if (windowHandle->getToken() == windowHandleToken) {
5197 return windowHandle;
5198 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005201 return nullptr;
5202 }
5203
Prabir Pradhan16463382023-10-12 23:03:19 +00005204 // Only look through the requested display.
5205 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005206 if (windowHandle->getToken() == windowHandleToken) {
5207 return windowHandle;
5208 }
5209 }
5210 return nullptr;
5211}
5212
chaviw98318de2021-05-19 16:45:23 -05005213sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5214 const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08005215 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005216 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005217 if (handle->getId() == windowHandle->getId() &&
5218 handle->getToken() == windowHandle->getToken()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005219 if (windowHandle->getInfo()->displayId != displayId) {
5220 ALOGE("Found window %s in display %s"
5221 ", but it should belong to display %s",
5222 windowHandle->getName().c_str(), displayId.toString().c_str(),
5223 windowHandle->getInfo()->displayId.toString().c_str());
Mady Mellor017bcd12020-06-23 19:12:00 +00005224 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005225 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 }
5228 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005229 return nullptr;
5230}
5231
Linnan Li13bf76a2024-05-05 19:18:02 +08005232sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(
5233 ui::LogicalDisplayId displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005234 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5235 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Linnan Li13bf76a2024-05-05 19:18:02 +08005238ui::Transform InputDispatcher::getTransformLocked(ui::LogicalDisplayId displayId) const {
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005239 auto displayInfoIt = mDisplayInfos.find(displayId);
5240 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5241 : kIdentityTransform;
5242}
5243
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005244bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5245 const MotionEntry& motionEntry) const {
5246 const WindowInfo& info = *window->getInfo();
5247
5248 // Skip spy window targets that are not valid for targeted injection.
5249 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005250 return false;
5251 }
5252
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005253 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5254 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5255 return false;
5256 }
5257
5258 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5259 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5260 window->getName().c_str());
5261 return false;
5262 }
5263
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005264 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005265 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005266 ALOGW("Not sending touch to %s because there's no corresponding connection",
5267 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005268 return false;
5269 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005270
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005271 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005272 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005273 return false;
5274 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005275
5276 // Drop events that can't be trusted due to occlusion
5277 const auto [x, y] = resolveTouchedPosition(motionEntry);
5278 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5279 if (!isTouchTrustedLocked(occlusionInfo)) {
5280 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005281 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005282 for (const auto& log : occlusionInfo.debugInfo) {
5283 ALOGD("%s", log.c_str());
5284 }
5285 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005286 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5287 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005288 return false;
5289 }
5290
5291 // Drop touch events if requested by input feature
5292 if (shouldDropInput(motionEntry, window)) {
5293 return false;
5294 }
5295
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005296 // Ignore touches if stylus is down anywhere on screen
5297 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5298 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5299 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5300 return false;
5301 }
5302
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005303 return true;
5304}
5305
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005306void InputDispatcher::updateWindowHandlesForDisplayLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005307 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5308 ui::LogicalDisplayId displayId) {
chaviw98318de2021-05-19 16:45:23 -05005309 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005310 // Remove all handles on a display if there are no windows left.
5311 mWindowHandlesByDisplay.erase(displayId);
5312 return;
5313 }
5314
5315 // Since we compare the pointer of input window handles across window updates, we need
5316 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005317 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5318 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5319 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005320 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005321 }
5322
chaviw98318de2021-05-19 16:45:23 -05005323 std::vector<sp<WindowInfoHandle>> newHandles;
5324 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005325 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005326 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005327 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005328 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005329 const bool canReceiveInput =
5330 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5331 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005332 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005333 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005334 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005335 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005336 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005337 }
5338
5339 if (info->displayId != displayId) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005340 ALOGE("Window %s updated by wrong display %s, should belong to display %s",
5341 handle->getName().c_str(), displayId.toString().c_str(),
5342 info->displayId.toString().c_str());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005343 continue;
5344 }
5345
Robert Carredd13602020-04-13 17:24:34 -07005346 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
Linnan Li13bf76a2024-05-05 19:18:02 +08005347 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005348 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005349 oldHandle->updateFrom(handle);
5350 newHandles.push_back(oldHandle);
5351 } else {
5352 newHandles.push_back(handle);
5353 }
5354 }
5355
5356 // Insert or replace
5357 mWindowHandlesByDisplay[displayId] = newHandles;
5358}
5359
Arthur Hungb92218b2018-08-14 12:00:21 +08005360/**
5361 * Called from InputManagerService, update window handle list by displayId that can receive input.
5362 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5363 * If set an empty list, remove all handles from the specific display.
5364 * For focused handle, check if need to change and send a cancel event to previous one.
5365 * For removed handle, check if need to send a cancel event if already in touch.
5366 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005367void InputDispatcher::setInputWindowsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005368 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5369 ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005370 if (DEBUG_FOCUS) {
5371 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005372 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005373 windowList += iwh->getName() + " ";
5374 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005375 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005376 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005377 ScopedSyntheticEventTracer traceContext(mTracer);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
Prabir Pradhand65552b2021-10-07 11:23:50 -07005379 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005380 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005381 const WindowInfo& info = *window->getInfo();
5382
5383 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005384 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005385 if (noInputWindow && window->getToken() != nullptr) {
5386 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5387 window->getName().c_str());
5388 window->releaseChannel();
5389 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005390
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005391 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005392 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5393 !info.inputConfig.test(
5394 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005395 "%s has feature SPY, but is not a trusted overlay.",
5396 window->getName().c_str());
5397
Prabir Pradhand65552b2021-10-07 11:23:50 -07005398 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005399 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5400 !info.inputConfig.test(
5401 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005402 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5403 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005404 }
5405
Arthur Hung72d8dc32020-03-28 00:48:39 +00005406 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005407 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005408 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409
chaviw98318de2021-05-19 16:45:23 -05005410 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005411
chaviw98318de2021-05-19 16:45:23 -05005412 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005413
Vishnu Nairc519ff72021-01-21 08:23:08 -08005414 std::optional<FocusResolver::FocusChanges> changes =
5415 mFocusResolver.setInputWindows(displayId, windowHandles);
5416 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005417 onFocusChangedLocked(*changes, traceContext.getTracker(), removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419
Linnan Li72352222024-04-12 18:55:57 +08005420 if (const auto& it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
5421 TouchState& state = it->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005422 for (size_t i = 0; i < state.windows.size();) {
5423 TouchedWindow& touchedWindow = state.windows[i];
Linnan Li72352222024-04-12 18:55:57 +08005424 if (getWindowHandleLocked(touchedWindow.windowHandle) != nullptr) {
5425 i++;
5426 continue;
5427 }
5428 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5429 << " in display %" << displayId;
5430 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5431 "touched window was removed", traceContext.getTracker());
5432 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5433 // Since we are about to drop the touch, cancel the events for the wallpaper as
5434 // well.
5435 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5436 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5437 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5438 for (const DeviceId deviceId : touchedWindow.getTouchingDeviceIds()) {
5439 if (const auto& ww = state.getWallpaperWindow(deviceId); ww != nullptr) {
5440 options.deviceId = deviceId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005441 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 }
Linnan Li72352222024-04-12 18:55:57 +08005445 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
arthurhungb89ccb02020-12-30 16:19:01 +08005447
arthurhung6d4bed92021-03-17 11:59:33 +08005448 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005449 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005450 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005451 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005452 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005453 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5454 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005455 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005456 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005457 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005458
Siarhei Vishniakoub711e652024-08-12 12:00:28 -07005459 // Check if the hovering should stop because the window is no longer eligible to receive it
5460 // (for example, if the touchable region changed)
5461 if (const auto& it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
5462 TouchState& state = it->second;
5463 for (TouchedWindow& touchedWindow : state.windows) {
5464 std::vector<DeviceId> erasedDevices = touchedWindow.eraseHoveringPointersIf(
5465 [this, displayId, &touchedWindow](const PointerProperties& properties, float x,
5466 float y) REQUIRES(mLock) {
5467 const bool isStylus = properties.toolType == ToolType::STYLUS;
5468 const ui::Transform displayTransform = getTransformLocked(displayId);
5469 const bool stillAcceptsTouch =
5470 windowAcceptsTouchAt(*touchedWindow.windowHandle->getInfo(),
5471 displayId, x, y, isStylus, displayTransform);
5472 return !stillAcceptsTouch;
5473 });
5474
5475 for (DeviceId deviceId : erasedDevices) {
5476 CancelationOptions options(CancelationOptions::Mode::CANCEL_HOVER_EVENTS,
5477 "WindowInfo changed",
5478 traceContext.getTracker());
5479 options.deviceId = deviceId;
5480 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5481 }
5482 }
5483 }
5484
Arthur Hung72d8dc32020-03-28 00:48:39 +00005485 // Release information for windows that are no longer present.
5486 // This ensures that unused input channels are released promptly.
5487 // Otherwise, they might stick around until the window handle is destroyed
5488 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005489 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005490 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005491 if (DEBUG_FOCUS) {
5492 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005493 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005494 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005495 }
chaviw291d88a2019-02-14 10:33:58 -08005496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497}
5498
5499void InputDispatcher::setFocusedApplication(
Linnan Li13bf76a2024-05-05 19:18:02 +08005500 ui::LogicalDisplayId displayId,
5501 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005502 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005503 ALOGD("setFocusedApplication displayId=%s %s", displayId.toString().c_str(),
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005504 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5505 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005507 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005508 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509 } // release lock
5510
5511 // Wake up poll loop since it may need to make new input dispatching choices.
5512 mLooper->wake();
5513}
5514
Vishnu Nair599f1412021-06-21 10:39:58 -07005515void InputDispatcher::setFocusedApplicationLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005516 ui::LogicalDisplayId displayId,
5517 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Vishnu Nair599f1412021-06-21 10:39:58 -07005518 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5519 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5520
5521 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5522 return; // This application is already focused. No need to wake up or change anything.
5523 }
5524
5525 // Set the new application handle.
5526 if (inputApplicationHandle != nullptr) {
5527 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5528 } else {
5529 mFocusedApplicationHandlesByDisplay.erase(displayId);
5530 }
5531
5532 // No matter what the old focused application was, stop waiting on it because it is
5533 // no longer focused.
5534 resetNoFocusedWindowTimeoutLocked();
5535}
5536
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005537void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5538 if (interval.count() < 0) {
5539 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5540 }
5541 std::scoped_lock _l(mLock);
5542 mMinTimeBetweenUserActivityPokes = interval;
5543}
5544
Tiger Huang721e26f2018-07-24 22:26:19 +08005545/**
5546 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5547 * the display not specified.
5548 *
5549 * We track any unreleased events for each window. If a window loses the ability to receive the
5550 * released event, we will send a cancel event to it. So when the focused display is changed, we
5551 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5552 * display. The display-specified events won't be affected.
5553 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005554void InputDispatcher::setFocusedDisplay(ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005555 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005556 ALOGD("setFocusedDisplay displayId=%s", displayId.toString().c_str());
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005557 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005558 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005559 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005560 ScopedSyntheticEventTracer traceContext(mTracer);
Tiger Huang721e26f2018-07-24 22:26:19 +08005561
5562 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005563 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005564 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005565 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005566 const auto windowHandle =
5567 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5568 if (windowHandle == nullptr) {
5569 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005570 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005571 CancelationOptions
5572 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005573 "The display which contains this window no longer has focus.",
5574 traceContext.getTracker());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005575 options.displayId = ui::LogicalDisplayId::INVALID;
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005576 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005577 }
5578 mFocusedDisplayId = displayId;
Arpit Singhb65e2bd2024-06-03 09:48:16 +00005579 // Enqueue a command to run outside the lock to tell the policy that the focused display
5580 // changed.
5581 auto command = [this]() REQUIRES(mLock) {
5582 scoped_unlock unlock(mLock);
5583 mPolicy.notifyFocusedDisplayChanged(mFocusedDisplayId);
5584 };
5585 postCommandLocked(std::move(command));
Tiger Huang721e26f2018-07-24 22:26:19 +08005586
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00005587 // Only a window on the focused display can have Pointer Capture, so disable the active
5588 // Pointer Capture session if there is one, since the focused display changed.
5589 disablePointerCaptureForcedLocked();
5590
Chris Ye3c2d6f52020-08-09 10:39:48 -07005591 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005592 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005593 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005594
Vishnu Nairad321cd2020-08-20 16:40:21 -07005595 if (newFocusedWindowToken == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005596 ALOGW("Focused display #%s does not have a focused window.",
5597 displayId.toString().c_str());
Vishnu Nairc519ff72021-01-21 08:23:08 -08005598 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005599 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005600 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005601 }
5602 }
5603 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005604 } // release lock
5605
5606 // Wake up poll loop since it may need to make new input dispatching choices.
5607 mLooper->wake();
5608}
5609
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005611 if (DEBUG_FOCUS) {
5612 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614
5615 bool changed;
5616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005617 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618
5619 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5620 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005621 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
5623
5624 if (mDispatchEnabled && !enabled) {
5625 resetAndDropEverythingLocked("dispatcher is being disabled");
5626 }
5627
5628 mDispatchEnabled = enabled;
5629 mDispatchFrozen = frozen;
5630 changed = true;
5631 } else {
5632 changed = false;
5633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 } // release lock
5635
5636 if (changed) {
5637 // Wake up poll loop since it may need to make new input dispatching choices.
5638 mLooper->wake();
5639 }
5640}
5641
5642void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005643 if (DEBUG_FOCUS) {
5644 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646
5647 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005648 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649
5650 if (mInputFilterEnabled == enabled) {
5651 return;
5652 }
5653
5654 mInputFilterEnabled = enabled;
5655 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5656 } // release lock
5657
5658 // Wake up poll loop since there might be work to do to drop everything.
5659 mLooper->wake();
5660}
5661
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005662bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Linnan Li13bf76a2024-05-05 19:18:02 +08005663 bool hasPermission, ui::LogicalDisplayId displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005664 bool needWake = false;
5665 {
5666 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005667 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005668 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08005669 "hasPermission=%s, target displayId=%s, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005670 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08005671 toString(hasPermission), displayId.toString().c_str(),
Antonio Kantek15beb512022-06-13 22:35:41 +00005672 mTouchModePerDisplay.count(displayId) == 0
5673 ? "not set"
5674 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5675
Antonio Kantek15beb512022-06-13 22:35:41 +00005676 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5677 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005678 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005679 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005680 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005681 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5682 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005683 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005684 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005685 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005686 return false;
5687 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005688 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005689 mTouchModePerDisplay[displayId] = inTouchMode;
5690 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5691 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005692 needWake = enqueueInboundEventLocked(std::move(entry));
5693 } // release lock
5694
5695 if (needWake) {
5696 mLooper->wake();
5697 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005698 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005699}
5700
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005701bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005702 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5703 if (focusedToken == nullptr) {
5704 return false;
5705 }
5706 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5707 return isWindowOwnedBy(windowHandle, pid, uid);
5708}
5709
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005710bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005711 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5712 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5713 const sp<WindowInfoHandle> windowHandle =
5714 getWindowHandleLocked(connectionToken);
5715 return isWindowOwnedBy(windowHandle, pid, uid);
5716 }) != mInteractionConnectionTokens.end();
5717}
5718
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005719void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5720 if (opacity < 0 || opacity > 1) {
5721 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5722 return;
5723 }
5724
5725 std::scoped_lock lock(mLock);
5726 mMaximumObscuringOpacityForTouch = opacity;
5727}
5728
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005729std::tuple<TouchState*, TouchedWindow*, ui::LogicalDisplayId>
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005730InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005731 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5732 for (TouchedWindow& w : state.windows) {
5733 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005734 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005735 }
5736 }
5737 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005738 return std::make_tuple(nullptr, nullptr, ui::LogicalDisplayId::DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005739}
5740
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005741std::tuple<const TouchState*, const TouchedWindow*, ui::LogicalDisplayId>
5742InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) const {
5743 return const_cast<InputDispatcher*>(this)->findTouchStateWindowAndDisplayLocked(token);
5744}
5745
5746bool InputDispatcher::windowHasTouchingPointersLocked(const sp<WindowInfoHandle>& windowHandle,
5747 DeviceId deviceId) const {
5748 const auto& [touchState, touchedWindow, _] =
5749 findTouchStateWindowAndDisplayLocked(windowHandle->getToken());
5750 if (touchState == nullptr) {
5751 // No touching pointers at all
5752 return false;
5753 }
5754 return touchState->hasTouchingPointers(deviceId);
5755}
5756
Prabir Pradhan367f3432024-02-13 23:05:58 +00005757bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5758 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005759 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005760 if (DEBUG_FOCUS) {
5761 ALOGD("Trivial transfer to same window.");
5762 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005763 return true;
5764 }
5765
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005767 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768
Arthur Hungabbb9d82021-09-01 14:52:30 +00005769 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005770 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005771
Arthur Hungabbb9d82021-09-01 14:52:30 +00005772 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005773 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 return false;
5775 }
Linnan Li72352222024-04-12 18:55:57 +08005776 std::set<DeviceId> deviceIds = touchedWindow->getTouchingDeviceIds();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005777 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005778 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5779 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005780 return false;
5781 }
Linnan Li72352222024-04-12 18:55:57 +08005782 const DeviceId deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005783
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005784 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5785 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5786 if (!toWindowHandle) {
5787 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005788 return false;
5789 }
5790
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005791 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005792 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005793 touchedWindow->windowHandle->getName().c_str(),
5794 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
Arthur Hungabbb9d82021-09-01 14:52:30 +00005797 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005798 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005799 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005800 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801
Arthur Hungabbb9d82021-09-01 14:52:30 +00005802 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005803 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005804 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005805 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005806 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005807 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005808 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005809 // Transferring touch focus using this API should not effect the focused window.
5810 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005811 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005812 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813
Arthur Hungabbb9d82021-09-01 14:52:30 +00005814 // Store the dragging window.
5815 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005816 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005817 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5818 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005819 return false;
5820 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005821 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005822 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005823 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824 }
5825
Arthur Hungabbb9d82021-09-01 14:52:30 +00005826 // Synthesize cancel for old window and down for new window.
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005827 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005828 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5829 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005830 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005831 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005832 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005833 "transferring touch from this window to another window",
5834 traceContext.getTracker());
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005835 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005836
5837 // Check if the wallpaper window should deliver the corresponding event.
5838 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005839 *state, deviceId, pointers, traceContext.getTracker());
Linnan Li72352222024-04-12 18:55:57 +08005840
5841 // Because new window may have a wallpaper window, it will merge input state from it
5842 // parent window, after this the firstNewPointerIdx in input state will be reset, then
5843 // it will cause new move event be thought inconsistent, so we should synthesize the
5844 // down event after it reset.
5845 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5846 newTargetFlags,
5847 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 } // release lock
5850
5851 // Wake up poll loop since it may need to make new input dispatching choices.
5852 mLooper->wake();
5853 return true;
5854}
5855
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005856/**
5857 * Get the touched foreground window on the given display.
5858 * Return null if there are no windows touched on that display, or if more than one foreground
5859 * window is being touched.
5860 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005861sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(
5862 ui::LogicalDisplayId displayId) const {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005863 auto stateIt = mTouchStatesByDisplay.find(displayId);
5864 if (stateIt == mTouchStatesByDisplay.end()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005865 ALOGI("No touch state on display %s", displayId.toString().c_str());
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005866 return nullptr;
5867 }
5868
5869 const TouchState& state = stateIt->second;
5870 sp<WindowInfoHandle> touchedForegroundWindow;
5871 // If multiple foreground windows are touched, return nullptr
5872 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005873 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005874 if (touchedForegroundWindow != nullptr) {
5875 ALOGI("Two or more foreground windows: %s and %s",
5876 touchedForegroundWindow->getName().c_str(),
5877 window.windowHandle->getName().c_str());
5878 return nullptr;
5879 }
5880 touchedForegroundWindow = window.windowHandle;
5881 }
5882 }
5883 return touchedForegroundWindow;
5884}
5885
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005886// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005887bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
Linnan Li13bf76a2024-05-05 19:18:02 +08005888 ui::LogicalDisplayId displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005889 sp<IBinder> fromToken;
5890 { // acquire lock
5891 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005892 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005893 if (toWindowHandle == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005894 ALOGW("Could not find window associated with token=%p on display %s",
5895 destChannelToken.get(), displayId.toString().c_str());
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005896 return false;
5897 }
5898
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005899 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5900 if (from == nullptr) {
5901 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5902 return false;
5903 }
5904
5905 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005906 } // release lock
5907
Prabir Pradhan367f3432024-02-13 23:05:58 +00005908 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005909}
5910
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005912 if (DEBUG_FOCUS) {
5913 ALOGD("Resetting and dropping all events (%s).", reason);
5914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005916 ScopedSyntheticEventTracer traceContext(mTracer);
5917 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason,
5918 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 synthesizeCancelationEventsForAllConnectionsLocked(options);
5920
5921 resetKeyRepeatLocked();
5922 releasePendingEventLocked();
5923 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005926 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005927 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928}
5929
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005930void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005931 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 dumpDispatchStateLocked(dump);
5933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005934 std::istringstream stream(dump);
5935 std::string line;
5936
5937 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005938 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 }
5940}
5941
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005942std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005943 std::string dump;
5944
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005945 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
Hiroki Sato25040232024-02-22 17:21:22 +09005946 toString(mCurrentPointerCaptureRequest.isEnable()));
Prabir Pradhan99987712020-11-10 18:43:05 -08005947
5948 std::string windowName = "None";
5949 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005950 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005951 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5952 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5953 : "token has capture without window";
5954 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005955 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005956
5957 return dump;
5958}
5959
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005960void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005961 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5962 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5963 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Linnan Li13bf76a2024-05-05 19:18:02 +08005964 dump += StringPrintf(INDENT "FocusedDisplayId: %s\n", mFocusedDisplayId.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965
Tiger Huang721e26f2018-07-24 22:26:19 +08005966 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5967 dump += StringPrintf(INDENT "FocusedApplications:\n");
5968 for (auto& it : mFocusedApplicationHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005969 const ui::LogicalDisplayId displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005970 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005971 const std::chrono::duration timeout =
5972 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Linnan Li13bf76a2024-05-05 19:18:02 +08005973 dump += StringPrintf(INDENT2 "displayId=%s, name='%s', dispatchingTimeout=%" PRId64
5974 "ms\n",
5975 displayId.toString().c_str(), applicationHandle->getName().c_str(),
5976 millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005979 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005981
Vishnu Nairc519ff72021-01-21 08:23:08 -08005982 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005983 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005985 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005986 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005987 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005988 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
Linnan Li13bf76a2024-05-05 19:18:02 +08005989 dump += INDENT2 + displayId.toString() + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 }
5991 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005992 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005993 }
5994
arthurhung6d4bed92021-03-17 11:59:33 +08005995 if (mDragState) {
5996 dump += StringPrintf(INDENT "DragState:\n");
5997 mDragState->dump(dump, INDENT2);
5998 }
5999
Arthur Hungb92218b2018-08-14 12:00:21 +08006000 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006001 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006002 dump += StringPrintf(INDENT "Display: %s\n", displayId.toString().c_str());
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006003 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
6004 const auto& displayInfo = it->second;
6005 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
6006 displayInfo.logicalHeight);
6007 displayInfo.transform.dump(dump, "transform", INDENT4);
6008 } else {
6009 dump += INDENT2 "No DisplayInfo found!\n";
6010 }
6011
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006012 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08006013 dump += INDENT2 "Windows:\n";
6014 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006015 dump += StringPrintf(INDENT3 "%zu: %s", i,
6016 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08006017 }
6018 } else {
6019 dump += INDENT2 "Windows: <none>\n";
6020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021 }
6022 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08006023 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 }
6025
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006026 if (!mGlobalMonitorsByDisplay.empty()) {
6027 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006028 dump += StringPrintf(INDENT "Global monitors on display %s:\n",
6029 displayId.toString().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00006030 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006033 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 }
6035
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006036 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
6038 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006039 if (!mRecentQueue.empty()) {
6040 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00006041 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006042 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006043 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006044 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 }
6046 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006047 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 }
6049
6050 // Dump event currently being dispatched.
6051 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006052 dump += INDENT "PendingEvent:\n";
6053 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006054 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006055 dump += StringPrintf(", age=%" PRId64 "ms\n",
6056 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006058 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059 }
6060
6061 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006062 if (!mInboundQueue.empty()) {
6063 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00006064 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006065 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006066 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006067 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 }
6069 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006070 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
6072
Prabir Pradhancef936d2021-07-21 16:17:52 +00006073 if (!mCommandQueue.empty()) {
6074 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
6075 } else {
6076 dump += INDENT "CommandQueue: <empty>\n";
6077 }
6078
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006079 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006080 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006081 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006082 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006083 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006084 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006085 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006086 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006087 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006089 if (!connection->outboundQueue.empty()) {
6090 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
6091 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006092 dump += dumpQueue(connection->outboundQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 }
6094
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006095 if (!connection->waitQueue.empty()) {
6096 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
6097 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006098 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006100 std::string inputStateDump = streamableToString(connection->inputState);
6101 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006102 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006103 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 }
6106 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006107 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108 }
6109
Antonio Kantek15beb512022-06-13 22:35:41 +00006110 if (!mTouchModePerDisplay.empty()) {
6111 dump += INDENT "TouchModePerDisplay:\n";
6112 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006113 dump += StringPrintf(INDENT2 "Display: %s TouchMode: %s\n",
6114 displayId.toString().c_str(), std::to_string(touchMode).c_str());
Antonio Kantek15beb512022-06-13 22:35:41 +00006115 }
6116 } else {
6117 dump += INDENT "TouchModePerDisplay: <none>\n";
6118 }
6119
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006120 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006121 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
6122 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
6123 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00006124 dump += mLatencyTracker.dump(INDENT2);
jioana24878b52024-09-10 10:13:27 +00006125 dump += mInputEventTimelineProcessor->dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00006126 dump += INDENT "InputTracer: ";
6127 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128}
6129
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07006130void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00006131 const size_t numMonitors = monitors.size();
6132 for (size_t i = 0; i < numMonitors; i++) {
6133 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006134 const std::shared_ptr<Connection>& connection = monitor.connection;
6135 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00006136 dump += "\n";
6137 }
6138}
6139
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006140class LooperEventCallback : public LooperCallback {
6141public:
6142 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
6143 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
6144
6145private:
6146 std::function<int(int events)> mCallback;
6147};
6148
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006149Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006150 if (DEBUG_CHANNEL_CREATION) {
6151 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
6152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006153
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006154 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006155 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006156 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006157
6158 if (result) {
6159 return base::Error(result) << "Failed to open input channel pair with name " << name;
6160 }
6161
Michael Wrightd02c5b62014-02-10 15:10:22 -08006162 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006163 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006164 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006165 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006166 std::shared_ptr<Connection> connection =
6167 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
6168 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006170 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
6171 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006172 ALOGE("Created a new connection, but the token %p is already known", token.get());
6173 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006174
6175 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6176 this, std::placeholders::_1, token);
6177
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006178 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006179 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 } // release lock
6181
6182 // Wake the looper because some connections have changed.
6183 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006184 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185}
6186
Linnan Li13bf76a2024-05-05 19:18:02 +08006187Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
6188 ui::LogicalDisplayId displayId, const std::string& name, gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006189 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006190 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006191 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006192 if (result) {
6193 return base::Error(result) << "Failed to open input channel pair with name " << name;
6194 }
6195
Michael Wright3dd60e22019-03-27 22:06:44 +00006196 { // acquire lock
6197 std::scoped_lock _l(mLock);
6198
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07006199 if (displayId < ui::LogicalDisplayId::DEFAULT) {
Garfield Tan15601662020-09-22 15:32:38 -07006200 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6201 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006202 }
6203
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006204 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006205 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006206 std::shared_ptr<Connection> connection =
6207 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6208 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006209
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006210 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6211 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006212 ALOGE("Created a new connection, but the token %p is already known", token.get());
6213 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006214
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006215 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6216 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006217
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006218 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006219
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006220 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006221 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006222 }
Garfield Tan15601662020-09-22 15:32:38 -07006223
Michael Wright3dd60e22019-03-27 22:06:44 +00006224 // Wake the looper because some connections have changed.
6225 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006226 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006227}
6228
Garfield Tan15601662020-09-22 15:32:38 -07006229status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006231 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232
Harry Cutts33476232023-01-30 19:57:29 +00006233 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 if (status) {
6235 return status;
6236 }
6237 } // release lock
6238
6239 // Wake the poll loop because removing the connection may have changed the current
6240 // synchronization state.
6241 mLooper->wake();
6242 return OK;
6243}
6244
Garfield Tan15601662020-09-22 15:32:38 -07006245status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6246 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006247 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006248 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006249 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 return BAD_VALUE;
6251 }
6252
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006253 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006254
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006256 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 }
6258
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006259 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260
6261 nsecs_t currentTime = now();
6262 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6263
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006264 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 return OK;
6266}
6267
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006268void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006269 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6270 auto& [displayId, monitors] = *it;
6271 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006272 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006273 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006274
Michael Wright3dd60e22019-03-27 22:06:44 +00006275 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006276 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006277 } else {
6278 ++it;
6279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 }
6281}
6282
Michael Wright3dd60e22019-03-27 22:06:44 +00006283status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006284 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006285 return pilferPointersLocked(token);
6286}
Michael Wright3dd60e22019-03-27 22:06:44 +00006287
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006288status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006289 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6290 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006291 LOG(WARNING)
6292 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006293 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006294 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006295
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006296 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006297 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006298 LOG(WARNING)
6299 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6300 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006301 return BAD_VALUE;
6302 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006303 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006304 if (deviceIds.empty()) {
6305 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006306 return BAD_VALUE;
6307 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006308
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006309 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006310 for (const DeviceId deviceId : deviceIds) {
6311 TouchState& state = *statePtr;
6312 TouchedWindow& window = *windowPtr;
6313 // Send cancel events to all the input channels we're stealing from.
6314 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006315 "input channel stole pointer stream", traceContext.getTracker());
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006316 options.deviceId = deviceId;
6317 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006318 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6319 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006320 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006321
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006322 std::string canceledWindows;
6323 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006324 if (w.windowHandle->getToken() != token) {
6325 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006326 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006327 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006328 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006329 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006330 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006331 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006332 << " is stealing input gesture for device " << deviceId << " from "
6333 << canceledWindows;
6334
6335 // Prevent the gesture from being sent to any other windows.
6336 // This only blocks relevant pointers to be sent to other windows
6337 window.addPilferingPointers(deviceId, pointerIds);
6338
6339 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006340 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006341 return OK;
6342}
6343
Prabir Pradhan99987712020-11-10 18:43:05 -08006344void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6345 { // acquire lock
6346 std::scoped_lock _l(mLock);
6347 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006348 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006349 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6350 windowHandle != nullptr ? windowHandle->getName().c_str()
6351 : "token without window");
6352 }
6353
Vishnu Nairc519ff72021-01-21 08:23:08 -08006354 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006355 if (focusedToken != windowToken) {
6356 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6357 enabled ? "enable" : "disable");
6358 return;
6359 }
6360
Hiroki Sato25040232024-02-22 17:21:22 +09006361 if (enabled == mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006362 ALOGW("Ignoring request to %s Pointer Capture: "
6363 "window has %s requested pointer capture.",
6364 enabled ? "enable" : "disable", enabled ? "already" : "not");
6365 return;
6366 }
6367
Christine Franksb768bb42021-11-29 12:11:31 -08006368 if (enabled) {
6369 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6370 mIneligibleDisplaysForPointerCapture.end(),
6371 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6372 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6373 return;
6374 }
6375 }
6376
Hiroki Sato25040232024-02-22 17:21:22 +09006377 setPointerCaptureLocked(enabled ? windowToken : nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08006378 } // release lock
6379
6380 // Wake the thread to process command entries.
6381 mLooper->wake();
6382}
6383
Linnan Li13bf76a2024-05-05 19:18:02 +08006384void InputDispatcher::setDisplayEligibilityForPointerCapture(ui::LogicalDisplayId displayId,
6385 bool isEligible) {
Christine Franksb768bb42021-11-29 12:11:31 -08006386 { // acquire lock
6387 std::scoped_lock _l(mLock);
6388 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6389 if (!isEligible) {
6390 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6391 }
6392 } // release lock
6393}
6394
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006395std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006396 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006397 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006398 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006399 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006400 }
6401 }
6402 }
6403 return std::nullopt;
6404}
6405
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006406std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6407 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006408 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006409 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006410 }
6411
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006412 for (const auto& [token, connection] : mConnectionsByToken) {
6413 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006414 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 }
6416 }
Robert Carr4e670e52018-08-15 13:26:12 -07006417
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006418 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419}
6420
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006421std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006422 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006423 if (connection == nullptr) {
6424 return "<nullptr>";
6425 }
6426 return connection->getInputChannelName();
6427}
6428
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006429void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006430 mAnrTracker.eraseToken(connection->getToken());
6431 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006432}
6433
Prabir Pradhancef936d2021-07-21 16:17:52 +00006434void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006435 const std::shared_ptr<Connection>& connection,
6436 uint32_t seq, bool handled,
6437 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006438 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006439 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006440
6441 { // Start critical section
6442 auto dispatchEntryIt =
6443 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6444 [seq](auto& e) { return e->seq == seq; });
6445 if (dispatchEntryIt == connection->waitQueue.end()) {
6446 return;
6447 }
6448
6449 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6450
6451 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6452 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006453 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006454 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6455 }
6456 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006457 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006458 dispatchEntry.deliveryTime, consumeTime, finishTime);
6459 }
6460
6461 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006462 fallbackKeyEntry =
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006463 afterKeyEventLockedInterruptable(connection, &dispatchEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006464 }
6465 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006466
6467 // Dequeue the event and start the next cycle.
6468 // Because the lock might have been released, it is possible that the
6469 // contents of the wait queue to have been drained, so we need to double-check
6470 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006471 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6472 [seq](auto& e) { return e->seq == seq; });
6473 if (entryIt != connection->waitQueue.end()) {
6474 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6475 connection->waitQueue.erase(entryIt);
6476
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006477 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006478 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6479 if (!connection->responsive) {
6480 connection->responsive = isConnectionResponsive(*connection);
6481 if (connection->responsive) {
6482 // The connection was unresponsive, and now it's responsive.
6483 processConnectionResponsiveLocked(*connection);
6484 }
6485 }
6486 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006487 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006488 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6489 // Only dispatch fallbacks if there is a window for the connection.
6490 if (windowHandle != nullptr) {
6491 const auto inputTarget =
6492 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6493 dispatchEntry->targetFlags,
6494 fallbackKeyEntry->downTime);
6495 if (inputTarget.has_value()) {
6496 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6497 *inputTarget);
6498 }
6499 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006500 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006501 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006502 }
6503
6504 // Start the next dispatch cycle for this connection.
6505 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506}
6507
Prabir Pradhancef936d2021-07-21 16:17:52 +00006508void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6509 const sp<IBinder>& newToken) {
6510 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6511 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006512 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006513 };
6514 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006515}
6516
Prabir Pradhancef936d2021-07-21 16:17:52 +00006517void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6518 auto command = [this, token, x, y]() REQUIRES(mLock) {
6519 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006520 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006521 };
6522 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006523}
6524
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006525void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006526 if (connection == nullptr) {
6527 LOG_ALWAYS_FATAL("Caller must check for nullness");
6528 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006529 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6530 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006531 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006532 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006533 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006534 return;
6535 }
6536 /**
6537 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6538 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6539 * has changed. This could cause newer entries to time out before the already dispatched
6540 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6541 * processes the events linearly. So providing information about the oldest entry seems to be
6542 * most useful.
6543 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006544 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6545 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006546 std::string reason =
6547 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006548 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006549 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006550 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006551 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006552 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006553
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006554 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6555
6556 // Stop waking up for events on this connection, it is already unresponsive
6557 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006558}
6559
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006560void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6561 std::string reason =
6562 StringPrintf("%s does not have a focused window", application->getName().c_str());
6563 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006564
Yabin Cui8eb9c552023-06-08 18:05:07 +00006565 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006566 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006567 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006568 };
6569 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006570}
6571
chaviw98318de2021-05-19 16:45:23 -05006572void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006573 const std::string& reason) {
6574 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6575 updateLastAnrStateLocked(windowLabel, reason);
6576}
6577
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006578void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6579 const std::string& reason) {
6580 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006581 updateLastAnrStateLocked(windowLabel, reason);
6582}
6583
6584void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6585 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006587 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 struct tm tm;
6589 localtime_r(&t, &tm);
6590 char timestr[64];
6591 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006592 mLastAnrState.clear();
6593 mLastAnrState += INDENT "ANR:\n";
6594 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006595 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6596 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006597 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598}
6599
Prabir Pradhancef936d2021-07-21 16:17:52 +00006600void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006601 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006602 const KeyEvent event = createKeyEvent(entry);
6603 nsecs_t delay = 0;
6604 { // release lock
6605 scoped_unlock unlock(mLock);
6606 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006607 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006608 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6609 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6610 std::to_string(t.duration().count()).c_str());
6611 }
6612 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613
6614 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006615 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006616 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006617 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006619 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006620 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622}
6623
Prabir Pradhancef936d2021-07-21 16:17:52 +00006624void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006625 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006626 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006627 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006628 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006629 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006630 };
6631 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006632}
6633
Prabir Pradhanedd96402022-02-15 01:46:16 -08006634void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006635 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006636 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006637 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006638 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006639 };
6640 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006641}
6642
6643/**
6644 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6645 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6646 * command entry to the command queue.
6647 */
6648void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6649 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006650 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006651 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006652 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006653 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006654 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006655 pid = findMonitorPidByTokenLocked(connectionToken);
6656 } else {
6657 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006658 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006659 reason.c_str());
6660 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6661 if (handle != nullptr) {
6662 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006663 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006664 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006665 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006666}
6667
6668/**
6669 * Tell the policy that a connection has become responsive so that it can stop ANR.
6670 */
6671void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006672 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006673 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006674 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006675 pid = findMonitorPidByTokenLocked(connectionToken);
6676 } else {
6677 // The connection is a window
6678 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6679 if (handle != nullptr) {
6680 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006681 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006682 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006683 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006684}
6685
Prabir Pradhan24047542023-11-02 17:14:59 +00006686std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006687 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry, bool handled) {
6688 // The dispatchEntry is currently valid, but it might point to a deleted object after we release
6689 // the lock. For simplicity, make copies of the data of interest here and assume that
6690 // 'dispatchEntry' is not valid after this section.
6691 // Hold a strong reference to the EventEntry to ensure it's valid for the duration of this
6692 // function, even if the DispatchEntry gets destroyed and releases its share of the ownership.
6693 std::shared_ptr<const EventEntry> eventEntry = dispatchEntry->eventEntry;
6694 const bool hasForegroundTarget = dispatchEntry->hasForegroundTarget();
6695 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(eventEntry));
6696 // To prevent misuse, ensure dispatchEntry is no longer valid.
6697 dispatchEntry = nullptr;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006698 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006699 if (!handled) {
6700 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006701 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006702 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006703 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006705
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006706 // Get the fallback key state.
6707 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006708 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006709 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006710 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006711 connection->inputState.removeFallbackKey(originalKeyCode);
6712 }
6713
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006714 if (handled || !hasForegroundTarget) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006715 // If the application handles the original key for which we previously
6716 // generated a fallback or if the window is not a foreground window,
6717 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006718 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006719 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006720 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6721 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6722 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6723 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6724 keyEntry.policyFlags);
6725 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006726 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006727 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728
6729 mLock.unlock();
6730
Prabir Pradhana41d2442023-04-20 21:30:40 +00006731 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006732 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6733 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006734 unhandledKeyFallback) {
6735 event = *unhandledKeyFallback;
6736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006737
6738 mLock.lock();
6739
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006740 // Cancel the fallback key, but only if we still have a window for the channel.
6741 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006742 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006743 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6744 if (windowHandle != nullptr) {
6745 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6746 "application handled the original non-fallback key "
6747 "or is no longer a foreground target, "
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006748 "canceling previously dispatched fallback key",
6749 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006750 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006751 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006753 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006754 connection->inputState.removeFallbackKey(originalKeyCode);
6755 }
6756 } else {
6757 // If the application did not handle a non-fallback key, first check
6758 // that we are in a good state to perform unhandled key event processing
6759 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006760 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006761 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006762 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6763 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6764 "since this is not an initial down. "
6765 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6766 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6767 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006768 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006770
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006771 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006772 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6773 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6774 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6775 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6776 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006777 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006778
6779 mLock.unlock();
6780
Prabir Pradhana41d2442023-04-20 21:30:40 +00006781 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006782 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6783 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006784 fb) {
6785 fallback = true;
6786 event = *fb;
6787 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006788
6789 mLock.lock();
6790
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006791 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006792 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006793 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006794 }
6795
6796 // Latch the fallback keycode for this key on an initial down.
6797 // The fallback keycode cannot change at any other point in the lifecycle.
6798 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006799 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006800 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006801 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006802 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006803 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006804 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006805 }
6806
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006807 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006808
6809 // Cancel the fallback key if the policy decides not to send it anymore.
6810 // We will continue to dispatch the key to the policy but we will no
6811 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006812 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6813 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006814 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6815 if (fallback) {
6816 ALOGD("Unhandled key event: Policy requested to send key %d"
6817 "as a fallback for %d, but on the DOWN it had requested "
6818 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006819 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006820 } else {
6821 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6822 "but on the DOWN it had requested to send %d. "
6823 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006824 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006825 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006826 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006827
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006828 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6829 if (windowHandle != nullptr) {
6830 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006831 "canceling fallback, policy no longer desires it",
6832 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006833 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006834 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006835 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006836
6837 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006838 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006839 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006840 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006841 }
6842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006843
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006844 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6845 {
6846 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006847 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006848 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006849 for (const auto& [key, value] : fallbackKeys) {
6850 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006851 }
6852 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6853 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006854 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006855 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006856
6857 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006858 // Return the fallback key that we want dispatched to the channel.
6859 std::unique_ptr<KeyEntry> newEntry =
6860 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6861 event.getEventTime(), event.getDeviceId(),
6862 event.getSource(), event.getDisplayId(),
6863 keyEntry.policyFlags, keyEntry.action,
6864 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6865 *fallbackKeyCode, event.getScanCode(),
6866 event.getMetaState(), event.getRepeatCount(),
6867 event.getDownTime());
Prabir Pradhana67623c2024-02-21 06:57:36 +00006868 if (mTracer) {
6869 newEntry->traceTracker =
6870 mTracer->traceDerivedEvent(*newEntry, *keyEntry.traceTracker);
6871 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006872 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6873 ALOGD("Unhandled key event: Dispatching fallback key. "
6874 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006875 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006876 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006877 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006878 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006879 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6880 ALOGD("Unhandled key event: No fallback key.");
6881 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006882
6883 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006884 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006885 }
6886 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006887 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006888}
6889
Michael Wrightd02c5b62014-02-10 15:10:22 -08006890void InputDispatcher::traceInboundQueueLengthLocked() {
6891 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006892 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006893 }
6894}
6895
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006896void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006897 if (ATRACE_ENABLED()) {
6898 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006899 snprintf(counterName, sizeof(counterName), "oq:%s",
6900 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006901 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006902 }
6903}
6904
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006905void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006906 if (ATRACE_ENABLED()) {
6907 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006908 snprintf(counterName, sizeof(counterName), "wq:%s",
6909 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006910 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006911 }
6912}
6913
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006914void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006915 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006917 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006918 dumpDispatchStateLocked(dump);
6919
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006920 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006921 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006922 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006923 }
6924}
6925
6926void InputDispatcher::monitor() {
6927 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006928 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006929 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006930 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006931}
6932
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006933/**
6934 * Wake up the dispatcher and wait until it processes all events and commands.
6935 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6936 * this method can be safely called from any thread, as long as you've ensured that
6937 * the work you are interested in completing has already been queued.
6938 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006939bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006940 /**
6941 * Timeout should represent the longest possible time that a device might spend processing
6942 * events and commands.
6943 */
6944 constexpr std::chrono::duration TIMEOUT = 100ms;
6945 std::unique_lock lock(mLock);
6946 mLooper->wake();
6947 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6948 return result == std::cv_status::no_timeout;
6949}
6950
Vishnu Naire798b472020-07-23 13:52:21 -07006951/**
6952 * Sets focus to the window identified by the token. This must be called
6953 * after updating any input window handles.
6954 *
6955 * Params:
6956 * request.token - input channel token used to identify the window that should gain focus.
6957 * request.focusedToken - the token that the caller expects currently to be focused. If the
6958 * specified token does not match the currently focused window, this request will be dropped.
6959 * If the specified focused token matches the currently focused window, the call will succeed.
6960 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6961 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6962 * when requesting the focus change. This determines which request gets
6963 * precedence if there is a focus change request from another source such as pointer down.
6964 */
Vishnu Nair958da932020-08-21 17:12:37 -07006965void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6966 { // acquire lock
6967 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006968 std::optional<FocusResolver::FocusChanges> changes =
Linnan Li13bf76a2024-05-05 19:18:02 +08006969 mFocusResolver.setFocusedWindow(request,
6970 getWindowHandlesLocked(
6971 ui::LogicalDisplayId{request.displayId}));
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006972 ScopedSyntheticEventTracer traceContext(mTracer);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006973 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006974 onFocusChangedLocked(*changes, traceContext.getTracker());
Vishnu Nair958da932020-08-21 17:12:37 -07006975 }
6976 } // release lock
6977 // Wake up poll loop since it may need to make new input dispatching choices.
6978 mLooper->wake();
6979}
6980
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006981void InputDispatcher::onFocusChangedLocked(
6982 const FocusResolver::FocusChanges& changes,
6983 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker,
6984 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006985 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006986 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6987 ? removedFocusedWindowHandle
6988 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6989 if (resolvedWindow == nullptr) {
6990 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006991 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006992 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006993 "focus left window", traceTracker);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006994 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6995 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006996 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006997 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006998 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006999 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07007000 }
7001
Vishnu Nairc519ff72021-01-21 08:23:08 -08007002 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00007003 // If a window has pointer capture, then it must have focus and must be on the top-focused
7004 // display. We need to ensure that this contract is upheld when pointer capture is being
7005 // disabled due to a loss of window focus. If the window loses focus before it loses pointer
7006 // capture, then the window can be in a state where it has pointer capture but not focus,
7007 // violating the contract. Therefore we must dispatch the pointer capture event before the
7008 // focus event. Since focus events are added to the front of the queue (above), we add the
7009 // pointer capture event to the front of the queue after the focus events are added. This
7010 // ensures the pointer capture event ends up at the front.
7011 disablePointerCaptureForcedLocked();
7012
Prabir Pradhancef936d2021-07-21 16:17:52 +00007013 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07007014 }
7015}
Vishnu Nair958da932020-08-21 17:12:37 -07007016
Prabir Pradhan99987712020-11-10 18:43:05 -08007017void InputDispatcher::disablePointerCaptureForcedLocked() {
Hiroki Sato25040232024-02-22 17:21:22 +09007018 if (!mCurrentPointerCaptureRequest.isEnable() && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007019 return;
7020 }
7021
7022 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
7023
Hiroki Sato25040232024-02-22 17:21:22 +09007024 if (mCurrentPointerCaptureRequest.isEnable()) {
7025 setPointerCaptureLocked(nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08007026 }
7027
7028 if (!mWindowTokenWithPointerCapture) {
7029 // No need to send capture changes because no window has capture.
7030 return;
7031 }
7032
7033 if (mPendingEvent != nullptr) {
7034 // Move the pending event to the front of the queue. This will give the chance
7035 // for the pending event to be dropped if it is a captured event.
7036 mInboundQueue.push_front(mPendingEvent);
7037 mPendingEvent = nullptr;
7038 }
7039
7040 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007041 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08007042 mInboundQueue.push_front(std::move(entry));
7043}
7044
Hiroki Sato25040232024-02-22 17:21:22 +09007045void InputDispatcher::setPointerCaptureLocked(const sp<IBinder>& windowToken) {
7046 mCurrentPointerCaptureRequest.window = windowToken;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007047 mCurrentPointerCaptureRequest.seq++;
7048 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00007049 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00007050 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00007051 };
7052 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08007053}
7054
Linnan Li13bf76a2024-05-05 19:18:02 +08007055void InputDispatcher::displayRemoved(ui::LogicalDisplayId displayId) {
Vishnu Nair599f1412021-06-21 10:39:58 -07007056 { // acquire lock
7057 std::scoped_lock _l(mLock);
7058 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00007059 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07007060 setFocusedApplicationLocked(displayId, nullptr);
7061 // Call focus resolver to clean up stale requests. This must be called after input windows
7062 // have been removed for the removed display.
7063 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08007064 // Reset pointer capture eligibility, regardless of previous state.
7065 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00007066 // Remove the associated touch mode state.
7067 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07007068 mVerifiersByDisplay.erase(displayId);
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00007069 mInputFilterVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07007070 } // release lock
7071
7072 // Wake up poll loop since it may need to make new input dispatching choices.
7073 mLooper->wake();
7074}
7075
Patrick Williamsd828f302023-04-28 17:52:08 -05007076void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08007077 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
7078 {
7079 // acquire lock
7080 std::scoped_lock _l(mLock);
7081 logDispatchStateLocked();
7082 }
7083 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
7084 result.error().message().c_str());
7085 };
chaviw15fab6f2021-06-07 14:15:52 -05007086 // The listener sends the windows as a flattened array. Separate the windows by display for
7087 // more convenient parsing.
Linnan Li13bf76a2024-05-05 19:18:02 +08007088 std::unordered_map<ui::LogicalDisplayId, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05007089 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05007090 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007091 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07007092 if (input_flags::split_all_touches()) {
7093 handlesPerDisplay[info.displayId]
7094 .back()
7095 ->editInfo()
7096 ->setInputConfig(android::gui::WindowInfo::InputConfig::PREVENT_SPLITTING,
7097 false);
7098 }
chaviw15fab6f2021-06-07 14:15:52 -05007099 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007100
7101 { // acquire lock
7102 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00007103
7104 // Ensure that we have an entry created for all existing displays so that if a displayId has
7105 // no windows, we can tell that the windows were removed from the display.
7106 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
7107 handlesPerDisplay[displayId];
7108 }
7109
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007110 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05007111 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007112 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
7113 }
7114
7115 for (const auto& [displayId, handles] : handlesPerDisplay) {
7116 setInputWindowsLocked(handles, displayId);
7117 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05007118
7119 if (update.vsyncId < mWindowInfosVsyncId) {
7120 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
7121 ", current update vsync id: %" PRId64,
7122 mWindowInfosVsyncId, update.vsyncId);
7123 }
7124 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007125 }
7126 // Wake up poll loop since it may need to make new input dispatching choices.
7127 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05007128}
7129
Vishnu Nair062a8672021-09-03 16:07:44 -07007130bool InputDispatcher::shouldDropInput(
7131 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007132 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
7133 (windowHandle->getInfo()->inputConfig.test(
7134 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07007135 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007136 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
Linnan Li13bf76a2024-05-05 19:18:02 +08007137 "display %s.",
Vishnu Nair062a8672021-09-03 16:07:44 -07007138 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007139 windowHandle->getInfo()->inputConfig.string().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08007140 windowHandle->getInfo()->displayId.toString().c_str());
Vishnu Nair062a8672021-09-03 16:07:44 -07007141 return true;
7142 }
7143 return false;
7144}
7145
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007146void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05007147 const gui::WindowInfosUpdate& update) {
7148 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007149}
7150
Arthur Hungdfd528e2021-12-08 13:23:04 +00007151void InputDispatcher::cancelCurrentTouch() {
7152 {
7153 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007154 ScopedSyntheticEventTracer traceContext(mTracer);
Arthur Hungdfd528e2021-12-08 13:23:04 +00007155 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00007156 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007157 "cancel current touch", traceContext.getTracker());
Arthur Hungdfd528e2021-12-08 13:23:04 +00007158 synthesizeCancelationEventsForAllConnectionsLocked(options);
7159
7160 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00007161 }
7162 // Wake up poll loop since there might be work to do.
7163 mLooper->wake();
7164}
7165
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007166void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
7167 std::scoped_lock _l(mLock);
7168 mMonitorDispatchingTimeout = timeout;
7169}
7170
Arthur Hungc539dbb2022-12-08 07:45:36 +00007171void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
7172 const sp<WindowInfoHandle>& oldWindowHandle,
7173 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007174 TouchState& state, const MotionEntry& entry,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07007175 std::vector<InputTarget>& targets) const {
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007176 LOG_IF(FATAL, entry.getPointerCount() != 1) << "Entry not eligible for slip: " << entry;
7177 const DeviceId deviceId = entry.deviceId;
7178 const PointerProperties& pointerProperties = entry.pointerProperties[0];
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007179 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00007180 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
7181 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7182 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
7183 newWindowHandle->getInfo()->inputConfig.test(
7184 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7185 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007186 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007187 const sp<WindowInfoHandle> newWallpaper =
7188 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
7189 if (oldWallpaper == newWallpaper) {
7190 return;
7191 }
7192
7193 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08007194 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007195 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007196 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007197 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007198 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007199 }
7200
7201 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007202 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
7203 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00007204 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007205 deviceId, pointers, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007206 }
7207}
7208
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007209void InputDispatcher::transferWallpaperTouch(
7210 ftl::Flags<InputTarget::Flags> oldTargetFlags,
7211 ftl::Flags<InputTarget::Flags> newTargetFlags, const sp<WindowInfoHandle> fromWindowHandle,
Linnan Li72352222024-04-12 18:55:57 +08007212 const sp<WindowInfoHandle> toWindowHandle, TouchState& state, DeviceId deviceId,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007213 const std::vector<PointerProperties>& pointers,
7214 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00007215 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7216 fromWindowHandle->getInfo()->inputConfig.test(
7217 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7218 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7219 toWindowHandle->getInfo()->inputConfig.test(
7220 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7221
7222 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007223 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007224 const sp<WindowInfoHandle> newWallpaper =
7225 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
7226 if (oldWallpaper == newWallpaper) {
7227 return;
7228 }
7229
7230 if (oldWallpaper != nullptr) {
7231 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007232 "transferring touch focus to another window", traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007233 state.removeWindowByToken(oldWallpaper->getToken());
7234 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7235 }
7236
7237 if (newWallpaper != nullptr) {
7238 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007239 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7240 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007241 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7242 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007243 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007244 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007245 std::shared_ptr<Connection> wallpaperConnection =
7246 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007247 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007248 std::shared_ptr<Connection> toConnection =
7249 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007250 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7251 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007252 wallpaperFlags, traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007253 }
7254 }
7255}
7256
7257sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7258 const sp<WindowInfoHandle>& windowHandle) const {
7259 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7260 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7261 bool foundWindow = false;
7262 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7263 if (!foundWindow && otherHandle != windowHandle) {
7264 continue;
7265 }
7266 if (windowHandle == otherHandle) {
7267 foundWindow = true;
7268 continue;
7269 }
7270
7271 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7272 return otherHandle;
7273 }
7274 }
7275 return nullptr;
7276}
7277
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007278void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
Asmita Poddar2808d7e2024-09-12 13:15:38 +00007279 std::chrono::nanoseconds delay,
7280 bool keyRepeatEnabled) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007281 std::scoped_lock _l(mLock);
7282
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007283 mConfig.keyRepeatTimeout = timeout.count();
7284 mConfig.keyRepeatDelay = delay.count();
Asmita Poddar2808d7e2024-09-12 13:15:38 +00007285 mConfig.keyRepeatEnabled = keyRepeatEnabled;
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007286}
7287
Linnan Li13bf76a2024-05-05 19:18:02 +08007288bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token,
7289 ui::LogicalDisplayId displayId, DeviceId deviceId,
7290 int32_t pointerId) {
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007291 std::scoped_lock _l(mLock);
7292 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7293 if (touchStateIt == mTouchStatesByDisplay.end()) {
7294 return false;
7295 }
7296 for (const TouchedWindow& window : touchStateIt->second.windows) {
7297 if (window.windowHandle->getToken() == token &&
7298 (window.hasTouchingPointer(deviceId, pointerId) ||
7299 window.hasHoveringPointer(deviceId, pointerId))) {
7300 return true;
7301 }
7302 }
7303 return false;
7304}
7305
Prabir Pradhan04a66422024-03-15 22:45:27 +00007306void InputDispatcher::setInputMethodConnectionIsActive(bool isActive) {
7307 std::scoped_lock _l(mLock);
7308 if (mTracer) {
7309 mTracer->setInputMethodConnectionIsActive(isActive);
7310 }
7311}
7312
Garfield Tane84e6f92019-08-29 17:28:41 -07007313} // namespace android::inputdispatcher