blob: 4b43c277b6ce562019cbffddcd99b471d8bb3071 [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) {
jioana24878b52024-09-10 10:13:27 +00001034 const nsecs_t nextStatisticsPush = processLatencyStatisticsLocked();
1035 nextWakeupTime = std::min(nextWakeupTime, nextStatisticsPush);
1036 }
1037
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001038 // We are about to enter an infinitely long sleep, because we have no commands or
1039 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -07001040 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001041 mDispatcherEnteredIdle.notify_all();
1042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 } // release lock
1044
1045 // Wait for callback or timeout or wake. (make sure we round up, not down)
1046 nsecs_t currentTime = now();
1047 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
1048 mLooper->pollOnce(timeoutMillis);
1049}
1050
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001051/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001052 * Raise ANR if there is no focused window.
1053 * Before the ANR is raised, do a final state check:
1054 * 1. The currently focused application must be the same one we are waiting for.
1055 * 2. Ensure we still don't have a focused window.
1056 */
1057void InputDispatcher::processNoFocusedWindowAnrLocked() {
1058 // Check if the application that we are waiting for is still focused.
1059 std::shared_ptr<InputApplicationHandle> focusedApplication =
1060 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
1061 if (focusedApplication == nullptr ||
1062 focusedApplication->getApplicationToken() !=
1063 mAwaitedFocusedApplication->getApplicationToken()) {
1064 // Unexpected because we should have reset the ANR timer when focused application changed
1065 ALOGE("Waited for a focused window, but focused application has already changed to %s",
1066 focusedApplication->getName().c_str());
1067 return; // The focused application has changed.
1068 }
1069
chaviw98318de2021-05-19 16:45:23 -05001070 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001071 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
1072 if (focusedWindowHandle != nullptr) {
1073 return; // We now have a focused window. No need for ANR.
1074 }
1075 onAnrLocked(mAwaitedFocusedApplication);
1076}
1077
1078/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001079 * Check if any of the connections' wait queues have events that are too old.
1080 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
1081 * Return the time at which we should wake up next.
1082 */
1083nsecs_t InputDispatcher::processAnrsLocked() {
1084 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001085 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001086 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1087 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1088 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001089 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001090 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001091 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001092 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001093 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001094 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001095 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1096 }
1097 }
1098
1099 // Check if any connection ANRs are due
1100 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1101 if (currentTime < nextAnrCheck) { // most likely scenario
1102 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1103 }
1104
1105 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001106 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001107 if (connection == nullptr) {
1108 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1109 return nextAnrCheck;
1110 }
1111 connection->responsive = false;
1112 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001113 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001114 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001115 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001116}
1117
jioana24878b52024-09-10 10:13:27 +00001118/**
1119 * Check if enough time has passed since the last latency statistics push.
1120 * Return the time at which we should wake up next.
1121 */
1122nsecs_t InputDispatcher::processLatencyStatisticsLocked() {
1123 const nsecs_t currentTime = now();
1124 // Log the atom recording latency statistics if more than 6 hours passed from the last
1125 // push
1126 if (currentTime - mLastStatisticPushTime >= LATENCY_STATISTICS_PUSH_INTERVAL) {
1127 mInputEventTimelineProcessor->pushLatencyStatistics();
1128 mLastStatisticPushTime = currentTime;
1129 }
1130 return mLastStatisticPushTime + LATENCY_STATISTICS_PUSH_INTERVAL;
1131}
1132
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001133std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001134 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001135 if (connection->monitor) {
1136 return mMonitorDispatchingTimeout;
1137 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001138 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001139 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001140 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001141 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001142 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001143}
1144
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001145void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 nsecs_t currentTime = now();
1147
Jeff Browndc5992e2014-04-11 01:27:26 -07001148 // Reset the key repeat timer whenever normal dispatch is suspended while the
1149 // device is in a non-interactive state. This is to ensure that we abort a key
1150 // repeat if the device is just coming out of sleep.
1151 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 resetKeyRepeatLocked();
1153 }
1154
1155 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1156 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001157 if (DEBUG_FOCUS) {
1158 ALOGD("Dispatch frozen. Waiting some more.");
1159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 return;
1161 }
1162
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 // Ready to start a new event.
1164 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 // Synthesize a key repeat if appropriate.
1168 if (mKeyRepeatState.lastKeyEntry) {
1169 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1170 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1171 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001172 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
1174 }
1175
1176 // Nothing to do if there is no pending event.
1177 if (!mPendingEvent) {
1178 return;
1179 }
1180 } else {
1181 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001182 mPendingEvent = mInboundQueue.front();
1183 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 traceInboundQueueLengthLocked();
1185 }
1186
1187 // Poke user activity for this event.
1188 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001189 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192
1193 // Now we have an event to dispatch.
1194 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001195 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001197 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001199 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001201 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203
1204 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001205 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207
1208 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001209 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001210 const DeviceResetEntry& typedEntry =
1211 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001213 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 break;
1215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001217 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001218 std::shared_ptr<const FocusEntry> typedEntry =
1219 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001220 dispatchFocusLocked(currentTime, typedEntry);
1221 done = true;
1222 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1223 break;
1224 }
1225
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001226 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001227 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001228 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1229 done = true;
1230 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1231 break;
1232 }
1233
Prabir Pradhan99987712020-11-10 18:43:05 -08001234 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1235 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001236 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001237 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1238 done = true;
1239 break;
1240 }
1241
arthurhungb89ccb02020-12-30 16:19:01 +08001242 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001243 std::shared_ptr<const DragEntry> typedEntry =
1244 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001245 dispatchDragLocked(currentTime, typedEntry);
1246 done = true;
1247 break;
1248 }
1249
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001250 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001251 std::shared_ptr<const KeyEntry> keyEntry =
1252 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001254 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001256 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1257 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001259 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 break;
1261 }
1262
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001263 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001264 std::shared_ptr<const MotionEntry> motionEntry =
1265 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001267 // The event is stale. However, only drop stale events if there isn't an ongoing
1268 // gesture. That would allow us to complete the processing of the current stroke.
1269 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1270 if (touchStateIt != mTouchStatesByDisplay.end()) {
1271 const TouchState& touchState = touchStateIt->second;
1272 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1273 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1274 dropReason = DropReason::STALE;
1275 }
1276 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001277 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001278 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001279 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1280 // Only drop events that are focus-dispatched.
1281 dropReason = DropReason::BLOCKED;
1282 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
Chris Yef59a2f42020-10-16 12:55:26 -07001287
1288 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001289 std::shared_ptr<const SensorEntry> sensorEntry =
1290 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001291
Chris Yef59a2f42020-10-16 12:55:26 -07001292 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1293 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1294 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1295 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1296 dropReason = DropReason::STALE;
1297 }
1298 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1299 done = true;
1300 break;
1301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
1303
1304 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001305 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001306 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 }
Michael Wright3a981722015-06-10 15:26:13 +01001308 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001310 if (mTracer) {
1311 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
Prabir Pradhan4fc32e02024-06-14 16:00:58 +00001312 mTracer->eventProcessingComplete(*traceTracker, currentTime);
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001313 }
1314 }
1315
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001317 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
1319}
1320
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001321bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001322 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001323}
1324
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001325/**
1326 * Return true if the events preceding this incoming motion event should be dropped
1327 * Return false otherwise (the default behaviour)
1328 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001329bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001330 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001331 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001332
1333 // Optimize case where the current application is unresponsive and the user
1334 // decides to touch a window in a different application.
1335 // If the application takes too long to catch up then we drop all events preceding
1336 // the touch into the other window.
1337 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001338 const ui::LogicalDisplayId displayId = motionEntry.displayId;
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001339 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001340 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001341
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001342 sp<WindowInfoHandle> touchedWindowHandle =
1343 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001345 touchedWindowHandle->getApplicationToken() !=
1346 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001347 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001348 ALOGI("Pruning input queue because user touched a different application while waiting "
1349 "for %s",
1350 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001351 return true;
1352 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001353
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001354 // Alternatively, maybe there's a spy window that could handle this event.
1355 const std::vector<sp<WindowInfoHandle>> touchedSpies =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001356 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, motionEntry.deviceId);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001357 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001358 const std::shared_ptr<Connection> connection =
1359 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001360 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001361 // This spy window could take more input. Drop all events preceding this
1362 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001363 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001364 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001365 mAwaitedFocusedApplication->getName().c_str());
1366 return true;
1367 }
1368 }
1369 }
1370
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001371 return false;
1372}
1373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001375 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001376 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001377 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 traceInboundQueueLengthLocked();
1379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001381 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001382 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1383 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001384
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001385 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001386 if (mTracer) {
1387 ensureEventTraced(keyEntry);
1388 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001389
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001390 // If a new up event comes in, and the pending event with same key code has been asked
1391 // to try again later because of the policy. We have to reset the intercept key wake up
1392 // time for it may have been handled in the policy and could be dropped.
1393 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1394 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001395 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001396 if (pendingKey.keyCode == keyEntry.keyCode &&
1397 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001398 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1399 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001400 pendingKey.interceptKeyWakeupTime = 0;
1401 needWake = true;
1402 }
1403 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
1406
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001407 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001408 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1409 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001410 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1411 if (mTracer) {
1412 ensureEventTraced(motionEntry);
1413 }
1414 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001415 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001416 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001418
1419 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1420 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1421 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1422 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1423 // and some other events have not yet been processed, the dispatcher will wait for
1424 // these events to be processed before dispatching the key event. This is because
1425 // the unprocessed events may cause the focus to change (for example, by launching a
1426 // new window or tapping a different window). To prevent waiting too long, we force
1427 // the key to be sent to the currently focused window when a new tap comes in.
1428 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1429 "just send the pending key event to the currently focused window.");
1430 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001431 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001432 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001433 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001435 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001436 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1437 break;
1438 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001439 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001440 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001441 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001442 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1443 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001444 // nothing to do
1445 break;
1446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448
1449 return needWake;
1450}
1451
Prabir Pradhan24047542023-11-02 17:14:59 +00001452void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001453 // Do not store sensor event in recent queue to avoid flooding the queue.
1454 if (entry->type != EventEntry::Type::SENSOR) {
1455 mRecentQueue.push_back(entry);
1456 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001458 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 }
1460}
1461
Linnan Li13bf76a2024-05-05 19:18:02 +08001462sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(ui::LogicalDisplayId displayId,
1463 float x, float y, bool isStylus,
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001464 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001466 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001467 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001468 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001469 continue;
1470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001472 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001473 if (!info.isSpy() &&
1474 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001475 return windowHandle;
1476 }
1477 }
1478 return nullptr;
1479}
1480
1481std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08001482 ui::LogicalDisplayId displayId, const sp<WindowInfoHandle>& touchedWindow,
1483 int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001484 if (touchedWindow == nullptr) {
1485 return {};
1486 }
1487 // Traverse windows from front to back until we encounter the touched window.
1488 std::vector<InputTarget> outsideTargets;
1489 const auto& windowHandles = getWindowHandlesLocked(displayId);
1490 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1491 if (windowHandle == touchedWindow) {
1492 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1493 // below the touched window will not get ACTION_OUTSIDE event.
1494 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001495 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001496
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001497 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001498 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001499 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1500 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001501 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1502 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001503 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
1505 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001506 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507}
1508
Prabir Pradhand65552b2021-10-07 11:23:50 -07001509std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001510 ui::LogicalDisplayId displayId, float x, float y, bool isStylus, DeviceId deviceId) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001511 // Traverse windows from front to back and gather the touched spy windows.
1512 std::vector<sp<WindowInfoHandle>> spyWindows;
1513 const auto& windowHandles = getWindowHandlesLocked(displayId);
1514 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1515 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001516 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001517 // Generally, we would skip any pointer that's outside of the window. However, if the
1518 // spy prevents splitting, and already has some of the pointers from this device, then
1519 // it should get more pointers from the same device, even if they are outside of that
1520 // window
1521 if (info.supportsSplitTouch()) {
1522 continue;
1523 }
1524
1525 // We know that split touch is not supported. Skip this window only if it doesn't have
1526 // any touching pointers for this device already.
1527 if (!windowHasTouchingPointersLocked(windowHandle, deviceId)) {
1528 continue;
1529 }
1530 // If it already has pointers down for this device, then give it this pointer, too.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001531 }
1532 if (!info.isSpy()) {
1533 // The first touched non-spy window was found, so return the spy windows touched so far.
1534 return spyWindows;
1535 }
1536 spyWindows.push_back(windowHandle);
1537 }
1538 return spyWindows;
1539}
1540
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 const char* reason;
1543 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001544 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001545 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001546 ALOGD("Dropped event because policy consumed it.");
1547 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 reason = "inbound event was dropped because the policy consumed it";
1549 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001550 case DropReason::DISABLED:
1551 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 ALOGI("Dropped event because input dispatch is disabled.");
1553 }
1554 reason = "inbound event was dropped because input dispatch is disabled";
1555 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001556 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001557 LOG(INFO) << "Dropping because the current application is not responding and the user "
1558 "has started interacting with a different application: "
1559 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001560 reason = "inbound event was dropped because the current application is not responding "
1561 "and the user has started interacting with a different application";
1562 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001563 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 ALOGI("Dropped event because it is stale.");
1565 reason = "inbound event was dropped because it is stale";
1566 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001567 case DropReason::NO_POINTER_CAPTURE:
1568 ALOGI("Dropped event because there is no window with Pointer Capture.");
1569 reason = "inbound event was dropped because there is no window with Pointer Capture";
1570 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001571 case DropReason::NOT_DROPPED: {
1572 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001573 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 }
1576
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001578 case EventEntry::Type::KEY: {
Hu Guo3cfa7382023-11-15 09:50:04 +00001579 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001580 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason,
1581 keyEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001582 options.displayId = keyEntry.displayId;
1583 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001585 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001587 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1589 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001590 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason,
1591 motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001592 options.displayId = motionEntry.displayId;
1593 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001594 synthesizeCancelationEventsForAllConnectionsLocked(options);
1595 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001596 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001597 reason, motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001598 options.displayId = motionEntry.displayId;
1599 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001600 synthesizeCancelationEventsForAllConnectionsLocked(options);
1601 }
1602 break;
1603 }
Chris Yef59a2f42020-10-16 12:55:26 -07001604 case EventEntry::Type::SENSOR: {
1605 break;
1606 }
arthurhungb89ccb02020-12-30 16:19:01 +08001607 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1608 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 break;
1610 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001611 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001612 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001613 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001614 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001615 break;
1616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 }
1618}
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001621 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622}
1623
Prabir Pradhancef936d2021-07-21 16:17:52 +00001624bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001625 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 return false;
1627 }
1628
1629 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001630 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001631 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001632 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1633 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001634 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 return true;
1636}
1637
Prabir Pradhancef936d2021-07-21 16:17:52 +00001638void InputDispatcher::postCommandLocked(Command&& command) {
1639 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640}
1641
1642void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001643 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001644 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001645 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 releaseInboundEventLocked(entry);
1647 }
1648 traceInboundQueueLengthLocked();
1649}
1650
1651void InputDispatcher::releasePendingEventLocked() {
1652 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001654 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
1656}
1657
Prabir Pradhan24047542023-11-02 17:14:59 +00001658void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001659 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001660 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001661 if (DEBUG_DISPATCH_CYCLE) {
1662 ALOGD("Injected inbound event was dropped.");
1663 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001664 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 }
1666 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001667 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 }
1669 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670}
1671
1672void InputDispatcher::resetKeyRepeatLocked() {
1673 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001674 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 }
1676}
1677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001678std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001679 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
Michael Wright2e732952014-09-24 13:26:59 -07001681 uint32_t policyFlags = entry->policyFlags &
1682 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001685 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1686 currentTime, entry->deviceId, entry->source,
1687 entry->displayId, policyFlags, entry->action, entry->flags,
1688 entry->keyCode, entry->scanCode, entry->metaState,
1689 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001691 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001692 if (mTracer) {
1693 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1694 }
1695
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001696 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001698 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699}
1700
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001701bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1702 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001703 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1704 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1705 entry.deviceId);
1706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707
liushenxiang42232912021-05-21 20:24:09 +08001708 // Reset key repeating in case a keyboard device was disabled or enabled.
1709 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1710 resetKeyRepeatLocked();
1711 }
1712
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001713 ScopedSyntheticEventTracer traceContext(mTracer);
1714 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset",
1715 traceContext.getTracker());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001716 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001718
1719 // Remove all active pointers from this device
1720 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1721 touchState.removeAllPointersForDevice(entry.deviceId);
1722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 return true;
1724}
1725
Vishnu Nairad321cd2020-08-20 16:40:21 -07001726void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001727 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001728 if (mPendingEvent != nullptr) {
1729 // Move the pending event to the front of the queue. This will give the chance
1730 // for the pending event to get dispatched to the newly focused window
1731 mInboundQueue.push_front(mPendingEvent);
1732 mPendingEvent = nullptr;
1733 }
1734
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001735 std::unique_ptr<FocusEntry> focusEntry =
1736 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1737 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001738
1739 // This event should go to the front of the queue, but behind all other focus events
1740 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001741 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1742 [](const std::shared_ptr<const EventEntry>& event) {
1743 return event->type == EventEntry::Type::FOCUS;
1744 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001745
1746 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001748}
1749
Prabir Pradhan24047542023-11-02 17:14:59 +00001750void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1751 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001752 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1753 if (connection == nullptr) {
1754 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001755 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001756 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001757 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001758 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001759 std::string reason = std::string("reason=").append(entry->reason);
1760 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001761 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001762}
1763
Prabir Pradhan99987712020-11-10 18:43:05 -08001764void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001765 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001766 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001767 dropReason = DropReason::NOT_DROPPED;
1768
Prabir Pradhan99987712020-11-10 18:43:05 -08001769 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001770 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001771
Hiroki Sato25040232024-02-22 17:21:22 +09001772 if (entry->pointerCaptureRequest.isEnable()) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001773 // Enable Pointer Capture.
1774 if (haveWindowWithPointerCapture &&
1775 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001776 // This can happen if pointer capture is disabled and re-enabled before we notify the
1777 // app of the state change, so there is no need to notify the app.
1778 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1779 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001780 }
Hiroki Sato25040232024-02-22 17:21:22 +09001781 if (!mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001782 // This can happen if a window requests capture and immediately releases capture.
1783 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001784 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001785 return;
1786 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001787 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1788 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1789 return;
1790 }
1791
Vishnu Nairc519ff72021-01-21 08:23:08 -08001792 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001793 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
Hiroki Sato25040232024-02-22 17:21:22 +09001794 LOG_ALWAYS_FATAL_IF(token != entry->pointerCaptureRequest.window,
1795 "Unexpected requested window for Pointer Capture.");
Prabir Pradhan99987712020-11-10 18:43:05 -08001796 mWindowTokenWithPointerCapture = token;
1797 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001798 // Disable Pointer Capture.
1799 // We do not check if the sequence number matches for requests to disable Pointer Capture
1800 // for two reasons:
1801 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1802 // to disable capture with the same sequence number: one generated by
1803 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1804 // Capture being disabled in InputReader.
1805 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1806 // actual Pointer Capture state that affects events being generated by input devices is
1807 // in InputReader.
1808 if (!haveWindowWithPointerCapture) {
1809 // Pointer capture was already forcefully disabled because of focus change.
1810 dropReason = DropReason::NOT_DROPPED;
1811 return;
1812 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001813 token = mWindowTokenWithPointerCapture;
1814 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001815 if (mCurrentPointerCaptureRequest.isEnable()) {
1816 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001817 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001818 }
1819
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001820 auto connection = getConnectionLocked(token);
1821 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001822 // Window has gone away, clean up Pointer Capture state.
1823 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001824 if (mCurrentPointerCaptureRequest.isEnable()) {
1825 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001826 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001827 return;
1828 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001829 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001830 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001831
1832 dropReason = DropReason::NOT_DROPPED;
1833}
1834
Prabir Pradhan24047542023-11-02 17:14:59 +00001835void InputDispatcher::dispatchTouchModeChangeLocked(
1836 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001837 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001838 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001839 if (windowHandles.empty()) {
1840 return;
1841 }
1842 const std::vector<InputTarget> inputTargets =
1843 getInputTargetsFromWindowHandlesLocked(windowHandles);
1844 if (inputTargets.empty()) {
1845 return;
1846 }
1847 entry->dispatchInProgress = true;
1848 dispatchEventLocked(currentTime, entry, inputTargets);
1849}
1850
1851std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1852 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1853 std::vector<InputTarget> inputTargets;
1854 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001855 const sp<IBinder>& token = handle->getToken();
1856 if (token == nullptr) {
1857 continue;
1858 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001859 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1860 if (connection == nullptr) {
1861 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001862 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001863 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001864 }
1865 return inputTargets;
1866}
1867
Prabir Pradhan24047542023-11-02 17:14:59 +00001868bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001869 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001871 if (!entry->dispatchInProgress) {
Hu Guofe3c8f12023-09-22 17:20:15 +08001872 if (!entry->syntheticRepeat && entry->action == AKEY_EVENT_ACTION_DOWN &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001873 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1874 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1875 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001876 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 // We have seen two identical key downs in a row which indicates that the device
1878 // driver is automatically generating key repeats itself. We take note of the
1879 // repeat here, but we disable our own next key repeat timer since it is clear that
1880 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001881 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1882 // Make sure we don't get key down from a different device. If a different
1883 // device Id has same key pressed down, the new device Id will replace the
1884 // current one to hold the key repeat with repeat count reset.
1885 // In the future when got a KEY_UP on the device id, drop it and do not
1886 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1888 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001889 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 } else {
1891 // Not a repeat. Save key down state in case we do see a repeat later.
1892 resetKeyRepeatLocked();
1893 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1894 }
1895 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001896 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1897 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001898 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001899 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001900 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1901 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 resetKeyRepeatLocked();
1904 }
1905
1906 if (entry->repeatCount == 1) {
1907 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1908 } else {
1909 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1910 }
1911
1912 entry->dispatchInProgress = true;
1913
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 }
1916
1917 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001918 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001920 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 return false; // wait until next wakeup
1922 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001923 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 entry->interceptKeyWakeupTime = 0;
1925 }
1926
1927 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001928 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001930 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001931 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001932
1933 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1934 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1935 };
1936 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 return false; // wait for the command to run
1938 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001939 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001941 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001942 if (*dropReason == DropReason::NOT_DROPPED) {
1943 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 }
1945 }
1946
1947 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001948 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001949 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1951 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001952 mReporter->reportDroppedKey(entry->id);
Josep del Rioc8fdedb2024-05-21 13:32:43 +00001953 // Poke user activity for consumed keys, as it may have not been reported due to
1954 // the focused window requesting user activity to be disabled
1955 if (*dropReason == DropReason::POLICY &&
1956 mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
1957 pokeUserActivityLocked(*entry);
1958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 return true;
1960 }
1961
1962 // Identify targets.
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001963 Result<sp<WindowInfoHandle>, InputEventInjectionResult> result =
1964 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001966 if (!result.ok()) {
1967 if (result.error().code() == InputEventInjectionResult::PENDING) {
1968 return false;
1969 }
1970 setInjectionResult(*entry, result.error().code());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 return true;
1972 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001973 sp<WindowInfoHandle>& focusedWindow = *result;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001974 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1975
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07001976 setInjectionResult(*entry, InputEventInjectionResult::SUCCEEDED);
1977
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001979 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1980 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001982 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001983 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001985 if (mTracer) {
1986 ensureEventTraced(*entry);
1987 for (const auto& target : inputTargets) {
1988 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1989 }
1990 }
1991
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 // Dispatch the key.
1993 dispatchEventLocked(currentTime, entry, inputTargets);
1994 return true;
1995}
1996
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001997void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001998 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001999 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002000 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
2001 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Linnan Li13bf76a2024-05-05 19:18:02 +08002002 prefix, entry.eventTime, entry.deviceId, entry.source,
2003 entry.displayId.toString().c_str(), entry.policyFlags, entry.action, entry.flags,
2004 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount, entry.downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006}
2007
Prabir Pradhancef936d2021-07-21 16:17:52 +00002008void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002009 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002010 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002011 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
2012 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
2013 "source=0x%x, sensorType=%s",
2014 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08002015 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002016 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002017 auto command = [this, entry]() REQUIRES(mLock) {
2018 scoped_unlock unlock(mLock);
2019
2020 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00002021 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002022 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00002023 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
2024 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002025 };
2026 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07002027}
2028
2029bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002030 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
2031 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08002032 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002033 }
Chris Yef59a2f42020-10-16 12:55:26 -07002034 { // acquire lock
2035 std::scoped_lock _l(mLock);
2036
2037 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00002038 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07002039 if (entry->type == EventEntry::Type::SENSOR) {
2040 it = mInboundQueue.erase(it);
2041 releaseInboundEventLocked(entry);
2042 }
2043 }
2044 }
2045 return true;
2046}
2047
Prabir Pradhan24047542023-11-02 17:14:59 +00002048bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
2049 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002050 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002051 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002053 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 entry->dispatchInProgress = true;
2055
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002056 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
2059 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07002060 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002061 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002062 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
2063 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 return true;
2065 }
2066
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002067 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
2069 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002070 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002072 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 if (isPointerEvent) {
2074 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00002075
2076 if (mDragState &&
2077 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2078 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
2079 pilferPointersLocked(mDragState->dragWindow->getToken());
2080 }
2081
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002082 Result<std::vector<InputTarget>, InputEventInjectionResult> result =
2083 findTouchedWindowTargetsLocked(currentTime, *entry);
2084
2085 if (result.ok()) {
2086 inputTargets = std::move(*result);
2087 injectionResult = InputEventInjectionResult::SUCCEEDED;
2088 } else {
2089 injectionResult = result.error().code();
2090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 } else {
2092 // Non touch event. (eg. trackball)
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002093 Result<sp<WindowInfoHandle>, InputEventInjectionResult> result =
2094 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime);
2095 if (result.ok()) {
2096 sp<WindowInfoHandle>& focusedWindow = *result;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002097 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002098 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2099 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2100 inputTargets);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002101 injectionResult = InputEventInjectionResult::SUCCEEDED;
2102 } else {
2103 injectionResult = result.error().code();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002106 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 return false;
2108 }
2109
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002110 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002111 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002112 return true;
2113 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002115 CancelationOptions::Mode mode(
2116 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2117 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002118 CancelationOptions options(mode, "input event injection failed", entry->traceTracker);
Linnan Lid8150952024-01-26 18:07:17 +00002119 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002120 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 return true;
2122 }
2123
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002124 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002125 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002127 if (mTracer) {
2128 ensureEventTraced(*entry);
2129 for (const auto& target : inputTargets) {
2130 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2131 }
2132 }
2133
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 dispatchEventLocked(currentTime, entry, inputTargets);
2136 return true;
2137}
2138
chaviw98318de2021-05-19 16:45:23 -05002139void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002140 bool isExiting, const int32_t rawX,
2141 const int32_t rawY) {
2142 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002143 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002144 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2145 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002146
2147 enqueueInboundEventLocked(std::move(dragEntry));
2148}
2149
Prabir Pradhan24047542023-11-02 17:14:59 +00002150void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2151 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002152 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2153 if (connection == nullptr) {
2154 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002155 }
arthurhungb89ccb02020-12-30 16:19:01 +08002156 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002157 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002158}
2159
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002160void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002161 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002162 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002163 "action=%s, actionButton=0x%x, flags=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002164 "metaState=0x%x, buttonState=0x%x, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002165 prefix, entry.eventTime, entry.deviceId,
Linnan Li13bf76a2024-05-05 19:18:02 +08002166 inputEventSourceToString(entry.source).c_str(), entry.displayId.toString().c_str(),
2167 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002168 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002170 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002171 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002172 "x=%f, y=%f, pressure=%f, size=%f, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002173 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002174 i, entry.pointerProperties[i].id,
2175 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002176 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2177 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2178 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2179 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2180 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2181 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2182 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2183 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2184 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187}
2188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002189void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002190 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002192 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002193 if (DEBUG_DISPATCH_CYCLE) {
2194 ALOGD("dispatchEventToCurrentInputTargets");
2195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002197 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002198
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2200
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002201 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002203 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002204 std::shared_ptr<Connection> connection = inputTarget.connection;
2205 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 }
2207}
2208
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002209void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2211 // If the policy decides to close the app, we will get a channel removal event via
2212 // unregisterInputChannel, and will clean up the connection that way. We are already not
2213 // sending new pointers to the connection when it blocked, but focused events will continue to
2214 // pile up.
2215 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002216 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002217 if (connection->status != Connection::Status::NORMAL) {
2218 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002220 ScopedSyntheticEventTracer traceContext(mTracer);
Prabir Pradhanfc364722024-02-08 17:51:20 +00002221 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002222 "application not responding", traceContext.getTracker());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002223
2224 sp<WindowInfoHandle> windowHandle;
2225 if (!connection->monitor) {
2226 windowHandle = getWindowHandleLocked(connection->getToken());
2227 if (windowHandle == nullptr) {
2228 // The window that is receiving this ANR was removed, so there is no need to generate
2229 // cancellations, because the cancellations would have already been generated when
2230 // the window was removed.
2231 return;
2232 }
2233 }
2234 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235}
2236
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002238 if (DEBUG_FOCUS) {
2239 ALOGD("Resetting ANR timeouts.");
2240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
2242 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002244 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245}
2246
Tiger Huang721e26f2018-07-24 22:26:19 +08002247/**
2248 * Get the display id that the given event should go to. If this event specifies a valid display id,
2249 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2250 * Focused display is the display that the user most recently interacted with.
2251 */
Linnan Li13bf76a2024-05-05 19:18:02 +08002252ui::LogicalDisplayId InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002253 ui::LogicalDisplayId displayId{ui::LogicalDisplayId::INVALID};
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002255 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002256 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2257 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 break;
2259 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002260 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002261 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2262 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263 break;
2264 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002265 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002266 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002267 case EventEntry::Type::FOCUS:
Chris Yef59a2f42020-10-16 12:55:26 -07002268 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002269 case EventEntry::Type::SENSOR:
2270 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002271 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002272 return ui::LogicalDisplayId::INVALID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002274 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002275 return displayId == ui::LogicalDisplayId::INVALID ? mFocusedDisplayId : displayId;
Tiger Huang721e26f2018-07-24 22:26:19 +08002276}
2277
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002278bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2279 const char* focusedWindowName) {
2280 if (mAnrTracker.empty()) {
2281 // already processed all events that we waited for
2282 mKeyIsWaitingForEventsTimeout = std::nullopt;
2283 return false;
2284 }
2285
2286 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2287 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002288 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002289 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002290 std::chrono::duration_cast<std::chrono::nanoseconds>(
2291 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002292 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002293 return true;
2294 }
2295
2296 // We still have pending events, and already started the timer
2297 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2298 return true; // Still waiting
2299 }
2300
2301 // Waited too long, and some connection still hasn't processed all motions
2302 // Just send the key to the focused window
2303 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2304 focusedWindowName);
2305 mKeyIsWaitingForEventsTimeout = std::nullopt;
2306 return false;
2307}
2308
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002309Result<sp<WindowInfoHandle>, InputEventInjectionResult>
2310InputDispatcher::findFocusedWindowTargetLocked(nsecs_t currentTime, const EventEntry& entry,
2311 nsecs_t& nextWakeupTime) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002312 ui::LogicalDisplayId displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002313 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002314 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002315 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2316
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 // If there is no currently focused window and no focused application
2318 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002319 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2320 ALOGI("Dropping %s event because there is no focused window or focused application in "
Linnan Li13bf76a2024-05-05 19:18:02 +08002321 "display %s.",
2322 ftl::enum_string(entry.type).c_str(), displayId.toString().c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002323 return injectionError(InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Vishnu Nair062a8672021-09-03 16:07:44 -07002326 // Drop key events if requested by input feature
2327 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002328 return injectionError(InputEventInjectionResult::FAILED);
Vishnu Nair062a8672021-09-03 16:07:44 -07002329 }
2330
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002331 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2332 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2333 // start interacting with another application via touch (app switch). This code can be removed
2334 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2335 // an app is expected to have a focused window.
2336 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2337 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2338 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002339 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2340 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2341 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002342 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002343 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002344 ALOGW("Waiting because no window has focus but %s may eventually add a "
2345 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002346 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002347 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002348 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002349 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2350 // Already raised ANR. Drop the event
2351 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002352 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002353 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002354 } else {
2355 // Still waiting for the focused window
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002356 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002357 }
2358 }
2359
2360 // we have a valid, non-null focused window
2361 resetNoFocusedWindowTimeoutLocked();
2362
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 // Verify targeted injection.
2364 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2365 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002366 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 }
2368
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002369 if (focusedWindowHandle->getInfo()->inputConfig.test(
2370 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002371 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002372 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002373 }
2374
2375 // If the event is a key event, then we must wait for all previous events to
2376 // complete before delivering it because previous events may have the
2377 // side-effect of transferring focus to a different window and we want to
2378 // ensure that the following keys are sent to the new window.
2379 //
2380 // Suppose the user touches a button in a window then immediately presses "A".
2381 // If the button causes a pop-up window to appear then we want to ensure that
2382 // the "A" key is delivered to the new pop-up window. This is because users
2383 // often anticipate pending UI changes when typing on a keyboard.
2384 // To obtain this behavior, we must serialize key events with respect to all
2385 // prior input events.
2386 if (entry.type == EventEntry::Type::KEY) {
2387 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002388 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002389 return injectionError(InputEventInjectionResult::PENDING);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002392 // Success!
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002393 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394}
2395
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002396/**
2397 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2398 * that are currently unresponsive.
2399 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002400std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2401 const std::vector<Monitor>& monitors) const {
2402 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002403 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002404 [](const Monitor& monitor) REQUIRES(mLock) {
2405 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002406 if (!connection->responsive) {
2407 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002408 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002409 return false;
2410 }
2411 return true;
2412 });
2413 return responsiveMonitors;
2414}
2415
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002416base::Result<std::vector<InputTarget>, android::os::InputEventInjectionResult>
2417InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry& entry) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002418 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002420 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 // For security reasons, we defer updating the touch state until we are sure that
2422 // event injection will be allowed.
Linnan Li13bf76a2024-05-05 19:18:02 +08002423 const ui::LogicalDisplayId displayId = entry.displayId;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002425 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002427 // Copy current touch state into tempTouchState.
2428 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2429 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002430 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002431 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002432 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2433 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002434 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002435 }
2436
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002437 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002438
2439 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2440 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2441 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002442 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2443 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002444 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002445 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2446 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002447 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2448 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2449 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002450 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002451
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002452 if (newGesture) {
2453 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002454 }
2455
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002456 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2457 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2458 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 }
2460
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002461 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002462 if (wasDown) {
2463 // Started hovering, but the device is already down: reject the hover event
2464 LOG(ERROR) << "Got hover event " << entry.getDescription()
2465 << " but the device is already down " << oldState->dump();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002466 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002467 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002468 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2469 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002470 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002471 }
2472
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2474 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002475 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002476 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002477 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002478 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2479 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002480 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002481 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002482 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002483
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002484 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002485 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002486 }
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07002487 LOG_IF(INFO, newTouchedWindowHandle == nullptr)
2488 << "No new touched window at (" << std::format("{:.1f}, {:.1f}", x, y)
2489 << ") in display " << displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 // Handle the case where we did not find a window.
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07002491 if (!input_flags::split_all_touches()) {
2492 // If we are force splitting all touches, then touches outside of the window should
2493 // be dropped, even if this device already has pointers down in another window.
2494 if (newTouchedWindowHandle == nullptr) {
2495 // Try to assign the pointer to the first foreground window we find, if there is
2496 // one.
2497 newTouchedWindowHandle =
2498 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
2499 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002500 }
2501
Prabir Pradhan5735a322022-04-11 17:23:34 +00002502 // Verify targeted injection.
2503 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2504 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002505 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002506 }
2507
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002508 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002509 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002510 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2511 // New window supports splitting, but we should never split mouse events.
2512 isSplit = !isFromMouse;
2513 } else if (isSplit) {
2514 // New window does not support splitting but we have already split events.
2515 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002516 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2517 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002518 newTouchedWindowHandle = nullptr;
2519 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002520 } else {
2521 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002522 // be delivered to a new window which supports split touch. Pointers from a mouse device
2523 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002524 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002525 }
2526
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002527 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07002528 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, entry.deviceId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002529 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002530 // Process the foreground window first so that it is the first to receive the event.
2531 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002532 }
2533
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002534 if (newTouchedWindows.empty()) {
Siarhei Vishniakouac42d242024-06-28 10:43:53 -07002535 LOG(INFO) << "Dropping event because there is no touchable window at (" << x << ", "
2536 << y << ") on display " << displayId << ": " << entry;
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002537 return injectionError(InputEventInjectionResult::FAILED);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002538 }
2539
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002540 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002541 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002542 continue;
2543 }
2544
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002545 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002546 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakoub711e652024-08-12 12:00:28 -07002547 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer, x,
2548 y);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002549 }
2550
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002551 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002552 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002553
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002554 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2555 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002556 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002557 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002558
2559 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002561 }
2562 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002564 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002565 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002566 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002567
2568 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002569
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002570 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002571 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2572 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Siarhei Vishniakoue535f972024-03-29 14:55:21 -07002573 Result<void> addResult =
2574 tempTouchState.addOrUpdateWindow(windowHandle,
2575 InputTarget::DispatchMode::AS_IS,
2576 targetFlags, entry.deviceId, {pointer},
2577 isDownOrPointerDown
2578 ? std::make_optional(
2579 entry.eventTime)
2580 : std::nullopt);
2581 if (!addResult.ok()) {
2582 LOG(ERROR) << "Error while processing " << entry << " for "
2583 << windowHandle->getName();
2584 logDispatchStateLocked();
2585 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002586 // If this is the pointer going down and the touched window has a wallpaper
2587 // then also add the touched wallpaper windows so they are locked in for the
2588 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2589 // SCROLL because the wallpaper engine only supports touch events. We would need to
2590 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2591 // handle these events.
2592 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002593 windowHandle->getInfo()->inputConfig.test(
2594 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2595 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2596 if (wallpaper != nullptr) {
2597 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2598 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002599 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002600 if (isSplit) {
2601 wallpaperFlags |= InputTarget::Flags::SPLIT;
2602 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002603 tempTouchState.addOrUpdateWindow(wallpaper,
2604 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002605 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002606 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002607 }
2608 }
2609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002611
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002612 // If a window is already pilfering some pointers, give it this new pointer as well and
2613 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2614 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002615 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002616 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002617 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002618 // This window is already pilfering some pointers, and this new pointer is also
2619 // going to it. Therefore, take over this pointer and don't give it to anyone
2620 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002621 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002622 }
2623 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002624
2625 // Restrict all pilfered pointers to the pilfering windows.
2626 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 } else {
2628 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2629
2630 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002631 if (!tempTouchState.isDown(entry.deviceId) &&
2632 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002633 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2634 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2635 << " is not down or we previously dropped the pointer down event in "
2636 << "display " << displayId << ": " << entry.getDescription();
2637 }
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002638 return injectionError(InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 }
2640
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002641 // If the pointer is not currently hovering, then ignore the event.
2642 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2643 const int32_t pointerId = entry.pointerProperties[0].id;
2644 if (oldState == nullptr ||
2645 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2646 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2647 "display "
2648 << displayId << ": " << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002649 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002650 }
2651 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2652 }
2653
arthurhung6d4bed92021-03-17 11:59:33 +08002654 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002655
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002657 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Linnan Li49b2b202024-04-12 12:46:40 +08002658 tempTouchState.isSlippery(entry.deviceId)) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002659 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002660 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002661 sp<WindowInfoHandle> oldTouchedWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002662 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002663 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002664 sp<WindowInfoHandle> newTouchedWindowHandle =
2665 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002666
Prabir Pradhan5735a322022-04-11 17:23:34 +00002667 // Verify targeted injection.
2668 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2669 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002670 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002671 }
2672
Linnan Libf069a32024-02-29 17:22:59 +00002673 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002674 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002675 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002676 newTouchedWindowHandle = nullptr;
2677 }
2678
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002679 if (newTouchedWindowHandle != nullptr &&
2680 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002681 ALOGI("Touch is slipping out of window %s into window %s in display %s",
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002682 oldTouchedWindowHandle->getName().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08002683 newTouchedWindowHandle->getName().c_str(), displayId.toString().c_str());
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002684
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002686 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002687 const PointerProperties& pointer = entry.pointerProperties[0];
2688 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002689
2690 const TouchedWindow& touchedWindow =
2691 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002693 InputTarget::DispatchMode::SLIPPERY_EXIT,
2694 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002695 touchedWindow.getDownTimeInTarget(entry.deviceId),
2696 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697
2698 // Make a slippery entrance into the new window.
2699 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002700 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
2702
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002703 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002704 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002705 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002708 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 }
2710 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002711 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002712 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002713 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 }
2715
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002716 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2717 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002718 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002719 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002720
2721 // Check if the wallpaper window should deliver the corresponding event.
2722 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00002723 tempTouchState, entry, targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002724 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002725 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 }
2727 }
Arthur Hung96483742022-11-15 03:30:48 +00002728
2729 // Update the pointerIds for non-splittable when it received pointer down.
2730 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2731 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002732 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002733 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2734 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002735 // Ignore drag window for it should just track one pointer.
2736 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2737 continue;
2738 }
Siarhei Vishniakou96204462024-07-13 23:59:47 -07002739 if (!touchedWindow.hasTouchingPointers(entry.deviceId)) {
2740 continue;
2741 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002742 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002743 }
2744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 }
2746
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002747 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002748 {
2749 std::vector<TouchedWindow> hoveringWindows =
Siarhei Vishniakouf91f3c72024-08-12 09:58:04 -07002750 getHoveringWindowsLocked(oldState, tempTouchState, entry,
Siarhei Vishniakou8a69ace2024-08-13 18:04:40 +00002751 std::bind_front(&InputDispatcher::logDispatchStateLocked,
2752 this));
Linnan Li41859c42024-03-05 16:20:34 +00002753 // Hardcode to single hovering pointer for now.
2754 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2755 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002756 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002757 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2758 touchedWindow.targetFlags, pointerIds,
2759 touchedWindow.getDownTimeInTarget(entry.deviceId),
2760 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763
Prabir Pradhan5735a322022-04-11 17:23:34 +00002764 // Ensure that all touched windows are valid for injection.
2765 if (entry.injectionState != nullptr) {
2766 std::string errs;
2767 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002768 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2769 if (err) errs += "\n - " + *err;
2770 }
2771 if (!errs.empty()) {
2772 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002773 "%s:%s",
2774 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002775 return injectionError(InputEventInjectionResult::TARGET_MISMATCH);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002776 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002777 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002778
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002779 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2780 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002782 sp<WindowInfoHandle> foregroundWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002783 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Michael Wright3dd60e22019-03-27 22:06:44 +00002784 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002785 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002786 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002787 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002788 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002789 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002790 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2791 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 }
2794 }
2795 }
2796 }
2797
Harry Cuttsb166c002023-05-09 13:06:05 +00002798 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2799 // only want the system UI to handle these gestures.
2800 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2801 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2802 if (isTouchpadNavGesture) {
2803 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2804 }
2805
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002806 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002807 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002808 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002809 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002810 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002811 continue;
2812 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002813 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002814 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002815 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002816 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002817
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002818 // During targeted injection, only allow owned targets to receive events
2819 std::erase_if(targets, [&](const InputTarget& target) {
2820 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2821 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2822 if (err) {
2823 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2824 << ": " << (*err);
2825 return true;
2826 }
2827 return false;
2828 });
2829
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002830 if (targets.empty()) {
2831 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002832 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002833 }
2834
2835 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2836 // window that is actually receiving the entire gesture.
2837 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002838 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002839 })) {
2840 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2841 << entry.getDescription();
Siarhei Vishniakoue1855a92024-07-12 13:40:36 -07002842 return injectionError(InputEventInjectionResult::FAILED);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002843 }
2844
Prabir Pradhan502a7252023-12-01 16:11:24 +00002845 // Now that we have generated all of the input targets for this event, reset the dispatch
2846 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002847 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002848 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002849 }
2850
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002851 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002852 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002853 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002854 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002855 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002856 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002857 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002858 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2859 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002860 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2861 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2862 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
2864
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002865 // Save changes unless the action was scroll in which case the temporary touch
2866 // state was only valid for this one action.
2867 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002868 if (displayId >= ui::LogicalDisplayId::DEFAULT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002869 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002870 mTouchStatesByDisplay[displayId] = tempTouchState;
2871 } else {
2872 mTouchStatesByDisplay.erase(displayId);
2873 }
2874 }
2875
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002876 if (tempTouchState.windows.empty()) {
2877 mTouchStatesByDisplay.erase(displayId);
2878 }
2879
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002880 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881}
2882
Linnan Li13bf76a2024-05-05 19:18:02 +08002883void InputDispatcher::finishDragAndDrop(ui::LogicalDisplayId displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002884 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2885 // have an explicit reason to support it.
2886 constexpr bool isStylus = false;
2887
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002888 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002889 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002890 if (dropWindow) {
2891 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002892 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002893 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002894 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002895 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002896 }
2897 mDragState.reset();
2898}
2899
2900void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002901 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002902 return;
2903 }
2904
arthurhung6d4bed92021-03-17 11:59:33 +08002905 if (!mDragState->isStartDrag) {
2906 mDragState->isStartDrag = true;
2907 mDragState->isStylusButtonDownAtStart =
2908 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2909 }
2910
Arthur Hung54745652022-04-20 07:17:41 +00002911 // Find the pointer index by id.
2912 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002913 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002914 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2915 if (pointerProperties.id == mDragState->pointerId) {
2916 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002917 }
Arthur Hung54745652022-04-20 07:17:41 +00002918 }
arthurhung6d4bed92021-03-17 11:59:33 +08002919
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002920 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002921 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002922 }
2923
2924 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2925 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2926 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2927
2928 switch (maskedAction) {
2929 case AMOTION_EVENT_ACTION_MOVE: {
2930 // Handle the special case : stylus button no longer pressed.
2931 bool isStylusButtonDown =
2932 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2933 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2934 finishDragAndDrop(entry.displayId, x, y);
2935 return;
2936 }
2937
2938 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2939 // until we have an explicit reason to support it.
2940 constexpr bool isStylus = false;
2941
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002942 sp<WindowInfoHandle> hoverWindowHandle =
2943 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2944 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002945 // enqueue drag exit if needed.
2946 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2947 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2948 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002949 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002950 y);
2951 }
2952 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2953 }
2954 // enqueue drag location if needed.
2955 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002956 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002957 }
2958 break;
2959 }
2960
2961 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002962 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002963 break;
2964 }
2965 // The drag pointer is up.
2966 [[fallthrough]];
2967 case AMOTION_EVENT_ACTION_UP:
2968 finishDragAndDrop(entry.displayId, x, y);
2969 break;
2970 case AMOTION_EVENT_ACTION_CANCEL: {
2971 ALOGD("Receiving cancel when drag and drop.");
2972 sendDropWindowCommandLocked(nullptr, 0, 0);
2973 mDragState.reset();
2974 break;
2975 }
arthurhungb89ccb02020-12-30 16:19:01 +08002976 }
2977}
2978
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002979std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2980 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002981 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002982 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002983 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2984 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002985 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2986 return {};
2987 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002988 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002989 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002990 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002991 inputTarget.flags = targetFlags;
2992 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2993 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2994 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2995 if (displayInfoIt != mDisplayInfos.end()) {
2996 inputTarget.displayTransform = displayInfoIt->second.transform;
2997 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002998 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002999 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
3000 }
3001 return inputTarget;
3002}
3003
chaviw98318de2021-05-19 16:45:23 -05003004void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003005 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003006 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003007 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07003008 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003009 std::vector<InputTarget>::iterator it =
3010 std::find_if(inputTargets.begin(), inputTargets.end(),
3011 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003012 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003013 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00003014
chaviw98318de2021-05-19 16:45:23 -05003015 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003016
3017 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003018 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003019 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3020 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003021 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003022 return;
3023 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07003024 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003025 it = inputTargets.end() - 1;
3026 }
3027
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003028 if (it->flags != targetFlags) {
3029 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
3030 }
3031 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
3032 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
3033 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3034 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003035}
3036
3037void InputDispatcher::addPointerWindowTargetLocked(
3038 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003039 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
3040 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
3041 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003042 if (pointerIds.none()) {
3043 for (const auto& target : inputTargets) {
3044 LOG(INFO) << "Target: " << target;
3045 }
3046 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
3047 return;
3048 }
3049 std::vector<InputTarget>::iterator it =
3050 std::find_if(inputTargets.begin(), inputTargets.end(),
3051 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003052 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003053 });
3054
3055 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
3056 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
3057 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
3058 // input targets for hovering pointers and for touching pointers.
3059 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
3060 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003061 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003062 // Force the code below to create a new input target
3063 it = inputTargets.end();
3064 }
3065
3066 const WindowInfo* windowInfo = windowHandle->getInfo();
3067
3068 if (it == inputTargets.end()) {
3069 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003070 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3071 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003072 if (!target) {
3073 return;
3074 }
3075 inputTargets.push_back(*target);
3076 it = inputTargets.end() - 1;
3077 }
3078
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003079 if (it->dispatchMode != dispatchMode) {
3080 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
3081 << ftl::enum_string(dispatchMode) << ", it=" << *it;
3082 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003083 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003084 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
3085 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003086 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003087 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003088 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003089 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3090 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003091
Siarhei Vishniakou59967592024-04-01 16:17:46 -07003092 Result<void> result = it->addPointers(pointerIds, windowInfo->transform);
3093 if (!result.ok()) {
3094 logDispatchStateLocked();
3095 LOG(FATAL) << result.error().message();
3096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097}
3098
Michael Wright3dd60e22019-03-27 22:06:44 +00003099void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Linnan Li13bf76a2024-05-05 19:18:02 +08003100 ui::LogicalDisplayId displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003101 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3102 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003103
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003104 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003105 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003106 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3107 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003108 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3109 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003110 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003111 target.setDefaultPointerTransform(target.displayTransform);
3112 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
3114}
3115
Robert Carrc9bf1d32020-04-13 17:21:08 -07003116/**
3117 * Indicate whether one window handle should be considered as obscuring
3118 * another window handle. We only check a few preconditions. Actually
3119 * checking the bounds is left to the caller.
3120 */
chaviw98318de2021-05-19 16:45:23 -05003121static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3122 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003123 // Compare by token so cloned layers aren't counted
3124 if (haveSameToken(windowHandle, otherHandle)) {
3125 return false;
3126 }
3127 auto info = windowHandle->getInfo();
3128 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003129 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003130 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003131 } else if (otherInfo->alpha == 0 &&
3132 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003133 // Those act as if they were invisible, so we don't need to flag them.
3134 // We do want to potentially flag touchable windows even if they have 0
3135 // opacity, since they can consume touches and alter the effects of the
3136 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003137 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003138 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3139 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003140 } else if (info->ownerUid == otherInfo->ownerUid) {
3141 // If ownerUid is the same we don't generate occlusion events as there
3142 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003143 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003144 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003145 return false;
3146 } else if (otherInfo->displayId != info->displayId) {
3147 return false;
3148 }
3149 return true;
3150}
3151
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003152/**
3153 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3154 * untrusted, one should check:
3155 *
3156 * 1. If result.hasBlockingOcclusion is true.
3157 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3158 * BLOCK_UNTRUSTED.
3159 *
3160 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3161 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3162 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3163 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3164 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3165 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3166 *
3167 * If neither of those is true, then it means the touch can be allowed.
3168 */
3169InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
Linnan Li5e5645e2024-03-05 14:43:05 +00003170 const sp<WindowInfoHandle>& windowHandle, float x, float y) const {
chaviw98318de2021-05-19 16:45:23 -05003171 const WindowInfo* windowInfo = windowHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003172 ui::LogicalDisplayId displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003173 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003174 TouchOcclusionInfo info;
3175 info.hasBlockingOcclusion = false;
3176 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003177 info.obscuringUid = gui::Uid::INVALID;
3178 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003179 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003180 if (windowHandle == otherHandle) {
3181 break; // All future windows are below us. Exit early.
3182 }
chaviw98318de2021-05-19 16:45:23 -05003183 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li5e5645e2024-03-05 14:43:05 +00003184 if (canBeObscuredBy(windowHandle, otherHandle) &&
3185 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId)) &&
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003186 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003187 if (DEBUG_TOUCH_OCCLUSION) {
3188 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003189 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003190 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003191 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3192 // we perform the checks below to see if the touch can be propagated or not based on the
3193 // window's touch occlusion mode
3194 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3195 info.hasBlockingOcclusion = true;
3196 info.obscuringUid = otherInfo->ownerUid;
3197 info.obscuringPackage = otherInfo->packageName;
3198 break;
3199 }
3200 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003201 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003202 float opacity =
3203 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3204 // Given windows A and B:
3205 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3206 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3207 opacityByUid[uid] = opacity;
3208 if (opacity > info.obscuringOpacity) {
3209 info.obscuringOpacity = opacity;
3210 info.obscuringUid = uid;
3211 info.obscuringPackage = otherInfo->packageName;
3212 }
3213 }
3214 }
3215 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003216 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003217 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003218 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003219 return info;
3220}
3221
chaviw98318de2021-05-19 16:45:23 -05003222std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003223 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003224 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003225 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3226 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3227 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003228 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003229 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003230 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3231 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003232 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3233 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3234 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003235 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003236}
3237
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003238bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3239 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003240 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3241 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003242 return false;
3243 }
3244 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003245 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003246 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003247 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003248 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3249 return false;
3250 }
3251 return true;
3252}
3253
chaviw98318de2021-05-19 16:45:23 -05003254bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Linnan Li5e5645e2024-03-05 14:43:05 +00003255 float x, float y) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003256 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003257 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3258 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003259 if (windowHandle == otherHandle) {
3260 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 }
chaviw98318de2021-05-19 16:45:23 -05003262 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003263 if (canBeObscuredBy(windowHandle, otherHandle) &&
Linnan Li5e5645e2024-03-05 14:43:05 +00003264 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 return true;
3266 }
3267 }
3268 return false;
3269}
3270
chaviw98318de2021-05-19 16:45:23 -05003271bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003272 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003273 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3274 const WindowInfo* windowInfo = windowHandle->getInfo();
3275 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003276 if (windowHandle == otherHandle) {
3277 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003278 }
chaviw98318de2021-05-19 16:45:23 -05003279 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003280 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003281 return true;
3282 }
3283 }
3284 return false;
3285}
3286
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003287std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003288 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003289 if (applicationHandle != nullptr) {
3290 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003291 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292 } else {
3293 return applicationHandle->getName();
3294 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003295 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003296 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003298 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300}
3301
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003302void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003303 if (!isUserActivityEvent(eventEntry)) {
3304 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003305 return;
3306 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003307
3308 const int32_t eventType = getUserActivityEventType(eventEntry);
3309 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3310 // Note that we're directly getting the time diff between the current event and the previous
3311 // event. This is assuming that the first user event always happens at a timestamp that is
3312 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3313 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3314 // value than the potential first user activity event time, so this is ok.
3315 std::chrono::nanoseconds timeSinceLastEvent =
3316 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3317 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3318 return;
3319 }
3320 }
3321
Linnan Li13bf76a2024-05-05 19:18:02 +08003322 ui::LogicalDisplayId displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003323 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003324 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003325 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003326 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003327 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003328 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
3330 }
3331
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003332 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003333 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3335 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 return;
3337 }
Josep del Riob3981622023-04-18 15:49:45 +00003338 if (windowDisablingUserActivityInfo != nullptr) {
3339 if (DEBUG_DISPATCH_CYCLE) {
3340 ALOGD("Not poking user activity: disabled by window '%s'.",
3341 windowDisablingUserActivityInfo->name.c_str());
3342 }
3343 return;
3344 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003347 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003348 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3349 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 return;
3351 }
Josep del Riob3981622023-04-18 15:49:45 +00003352 // Don't inhibit events that were intercepted or are not passed to
3353 // the apps, like system shortcuts
3354 if (windowDisablingUserActivityInfo != nullptr &&
Josep del Rioc8fdedb2024-05-21 13:32:43 +00003355 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP) {
Josep del Riob3981622023-04-18 15:49:45 +00003356 if (DEBUG_DISPATCH_CYCLE) {
3357 ALOGD("Not poking user activity: disabled by window '%s'.",
3358 windowDisablingUserActivityInfo->name.c_str());
3359 }
3360 return;
3361 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003364 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003365 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003366 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003367 break;
3368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 }
3370
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003371 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003372 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3373 REQUIRES(mLock) {
3374 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003375 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003376 };
3377 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378}
3379
3380void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003381 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003382 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003383 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003384 ATRACE_NAME_IF(ATRACE_ENABLED(),
3385 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3386 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003388 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003389 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003390 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003391 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003392 inputTarget.getPointerInfoString().c_str());
3393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394
3395 // Skip this event if the connection status is not normal.
3396 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003397 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003398 if (DEBUG_DISPATCH_CYCLE) {
3399 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003400 connection->getInputChannelName().c_str(),
3401 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 return;
3404 }
3405
3406 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003407 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003408 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003409 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003410 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003412 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003413 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003414 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3415 logDispatchStateLocked();
3416 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3417 "target on connection "
3418 << connection->getInputChannelName() << " for "
3419 << originalMotionEntry.getDescription();
3420 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003421 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003422 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003423 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 if (!splitMotionEntry) {
3425 return; // split event was dropped
3426 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003427 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3428 std::string reason = std::string("reason=pointer cancel on split window");
3429 android_log_event_list(LOGTAG_INPUT_CANCEL)
3430 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3431 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003432 if (DEBUG_FOCUS) {
3433 ALOGD("channel '%s' ~ Split motion event.",
3434 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003435 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003436 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003437 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3438 std::move(splitMotionEntry),
3439 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 return;
3441 }
3442 }
3443
3444 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003445 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3446 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447}
3448
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003449void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3450 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3451 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003452 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003453 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3454 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003455 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003456
hongzuo liu95785e22022-09-06 02:51:35 +00003457 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003459 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
3461 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003462 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 startDispatchCycleLocked(currentTime, connection);
3464 }
3465}
3466
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003467void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003468 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003469 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003470 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3471 eventEntry->type == EventEntry::Type::MOTION;
3472 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3473 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3474 << inputTarget << " connection: " << connection->getInputChannelName()
3475 << " entry: " << eventEntry->getDescription();
3476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 // This is a new event.
3478 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003479 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003480 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
Prabir Pradhana67623c2024-02-21 06:57:36 +00003481 mWindowInfosVsyncId, mTracer.get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003483 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3484 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003485 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003487 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003488 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003489 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3490 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003491 LOG(WARNING) << "channel " << connection->getInputChannelName()
3492 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003493 return; // skip the inconsistent event
3494 }
3495 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003498 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003499 std::shared_ptr<const MotionEntry> resolvedMotion =
3500 std::static_pointer_cast<const MotionEntry>(eventEntry);
3501 {
3502 // Determine the resolved motion entry.
3503 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3504 int32_t resolvedAction = motionEntry.action;
3505 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003507 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003508 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003509 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003510 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003511 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003512 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003513 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003514 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003515 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003516 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3517 }
3518 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3519 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3520 motionEntry.displayId)) {
3521 if (DEBUG_DISPATCH_CYCLE) {
3522 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3523 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3524 "enter event";
3525 }
3526 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3527 }
3528
3529 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3530 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3531 }
3532 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3533 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3534 }
3535 if (dispatchEntry->targetFlags.test(
3536 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3537 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3538 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003539 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3540 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3541 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003542
3543 dispatchEntry->resolvedFlags = resolvedFlags;
3544 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003545 std::optional<std::vector<PointerProperties>> usingProperties;
3546 std::optional<std::vector<PointerCoords>> usingCoords;
3547 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3548 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3549 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3550 // the dispatcher, and therefore the coordinates of this event are currently
3551 // incorrect. These events should use the coordinates of the last dispatched
3552 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3553 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3554 std::optional<std::pair<std::vector<PointerProperties>,
3555 std::vector<PointerCoords>>>
3556 pointerInfo =
3557 connection->inputState.getPointersOfLastEvent(motionEntry,
3558 hovering);
3559 if (pointerInfo) {
3560 usingProperties = pointerInfo->first;
3561 usingCoords = pointerInfo->second;
3562 }
3563 }
Prabir Pradhana67623c2024-02-21 06:57:36 +00003564 {
3565 // Generate a new MotionEntry with a new eventId using the resolved action
3566 // and flags, and set it as the resolved entry.
3567 auto newEntry = std::make_shared<
3568 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3569 motionEntry.eventTime, motionEntry.deviceId,
3570 motionEntry.source, motionEntry.displayId,
3571 motionEntry.policyFlags, resolvedAction,
3572 motionEntry.actionButton, resolvedFlags,
3573 motionEntry.metaState, motionEntry.buttonState,
3574 motionEntry.classification, motionEntry.edgeFlags,
3575 motionEntry.xPrecision, motionEntry.yPrecision,
3576 motionEntry.xCursorPosition,
3577 motionEntry.yCursorPosition, motionEntry.downTime,
3578 usingProperties.value_or(
3579 motionEntry.pointerProperties),
3580 usingCoords.value_or(motionEntry.pointerCoords));
3581 if (mTracer) {
3582 ensureEventTraced(motionEntry);
3583 newEntry->traceTracker =
3584 mTracer->traceDerivedEvent(*newEntry,
3585 *motionEntry.traceTracker);
3586 }
3587 resolvedMotion = newEntry;
3588 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003589 if (ATRACE_ENABLED()) {
3590 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3591 ") to MotionEvent(id=0x%" PRIx32 ").",
3592 motionEntry.id, resolvedMotion->id);
3593 ATRACE_NAME(message.c_str());
3594 }
3595
3596 // Set the resolved motion entry in the DispatchEntry.
3597 dispatchEntry->eventEntry = resolvedMotion;
3598 eventEntry = resolvedMotion;
3599 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003602 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3603 // devices being active at the same time in the same window, so if a new device is
3604 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003605 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003606 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003607 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003608 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003609 << connection->getInputChannelName() << " with event "
3610 << cancelEvent->getDescription();
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003611 if (mTracer) {
3612 static_cast<MotionEntry&>(*cancelEvent).traceTracker =
3613 mTracer->traceDerivedEvent(*cancelEvent, *resolvedMotion->traceTracker);
3614 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003615 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003616 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhana67623c2024-02-21 06:57:36 +00003617 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId,
3618 mTracer.get());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003619
3620 // Send these cancel events to the queue before sending the event from the new
3621 // device.
3622 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3623 }
3624
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003625 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003627 LOG(WARNING) << "channel " << connection->getInputChannelName()
3628 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629 return; // skip the inconsistent event
3630 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003631 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003632 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003633 // Skip reporting pointer down outside focus to the policy.
3634 break;
3635 }
3636
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003637 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003638 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003639
3640 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003642 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003643 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003644 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3645 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003646 break;
3647 }
Chris Yef59a2f42020-10-16 12:55:26 -07003648 case EventEntry::Type::SENSOR: {
3649 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3650 break;
3651 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003652 case EventEntry::Type::DEVICE_RESET: {
3653 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003654 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003655 break;
3656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658
3659 // Remember that we are waiting for this dispatch to complete.
3660 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003661 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663
3664 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003665 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003666 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003667}
3668
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003669/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003670 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003671 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003672 * The first role is to log input interaction with windows, which helps determine what the user was
3673 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3674 * that user started interacting with launcher window, as well as any other window that received
3675 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3676 * when the set of tokens that received the event changes. It is not logged again as long as the
3677 * user is interacting with the same windows.
3678 *
3679 * The second role is to track input device activity for metrics collection. For each input event,
3680 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3681 * input_interaction logs, the device interaction is reported even when the set of interaction
3682 * tokens do not change.
3683 *
3684 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3685 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003686 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003687void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3688 const std::vector<InputTarget>& targets) {
3689 int32_t deviceId;
3690 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003691 // Skip ACTION_UP events, and all events other than keys and motions
3692 if (entry.type == EventEntry::Type::KEY) {
3693 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3694 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3695 return;
3696 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003697 deviceId = keyEntry.deviceId;
3698 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003699 } else if (entry.type == EventEntry::Type::MOTION) {
3700 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3701 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003702 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3703 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003704 return;
3705 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003706 deviceId = motionEntry.deviceId;
3707 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003708 } else {
3709 return; // Not a key or a motion
3710 }
3711
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003712 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003713 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003714 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003715 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003716 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003717 continue; // Skip windows that receive ACTION_OUTSIDE
3718 }
3719
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003720 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003721 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003722 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003723 if (target.windowHandle) {
3724 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3725 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003726 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003727
3728 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3729 REQUIRES(mLock) {
3730 scoped_unlock unlock(mLock);
3731 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3732 };
3733 postCommandLocked(std::move(command));
3734
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003735 if (newConnectionTokens == mInteractionConnectionTokens) {
3736 return; // no change
3737 }
3738 mInteractionConnectionTokens = newConnectionTokens;
3739
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003740 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003741 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003742 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003743 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003744 std::string message = "Interaction with: " + targetList;
3745 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003746 message += "<none>";
3747 }
3748 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3749}
3750
chaviwfd6d3512019-03-25 13:23:49 -07003751void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003752 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003753 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003754 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3755 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003756 return;
3757 }
3758
Vishnu Nairc519ff72021-01-21 08:23:08 -08003759 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003760 if (focusedToken == token) {
3761 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003762 return;
3763 }
3764
Prabir Pradhancef936d2021-07-21 16:17:52 +00003765 auto command = [this, token]() REQUIRES(mLock) {
3766 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003767 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003768 };
3769 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770}
3771
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003772status_t InputDispatcher::publishMotionEvent(Connection& connection,
3773 DispatchEntry& dispatchEntry) const {
3774 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3775 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3776
3777 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003778 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003779
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003780 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003781 // Set the X and Y offset and X and Y scale depending on the input source.
3782 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003783 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003784 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3785 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003786 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003787 scaledCoords[i] = motionEntry.pointerCoords[i];
3788 // Don't apply window scale here since we don't want scale to affect raw
3789 // coordinates. The scale will be sent back to the client and applied
3790 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003791 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003792 }
3793 usingCoords = scaledCoords;
3794 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003795 }
3796
3797 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3798
3799 // Publish the motion event.
3800 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003801 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3802 motionEntry.source, motionEntry.displayId, std::move(hmac),
3803 motionEntry.action, motionEntry.actionButton,
3804 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3805 motionEntry.metaState, motionEntry.buttonState,
3806 motionEntry.classification, dispatchEntry.transform,
3807 motionEntry.xPrecision, motionEntry.yPrecision,
3808 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3809 dispatchEntry.rawTransform, motionEntry.downTime,
3810 motionEntry.eventTime, motionEntry.getPointerCount(),
3811 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003812}
3813
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003815 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003816 ATRACE_NAME_IF(ATRACE_ENABLED(),
3817 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3818 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003819 if (DEBUG_DISPATCH_CYCLE) {
3820 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003823 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003824 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003826 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003827 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
3829 // Publish the event.
3830 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003831 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3832 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003833 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003834 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3835 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003836 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003837 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3838 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003841 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003842 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003843 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3844 keyEntry.deviceId, keyEntry.source,
3845 keyEntry.displayId, std::move(hmac),
3846 keyEntry.action, dispatchEntry->resolvedFlags,
3847 keyEntry.keyCode, keyEntry.scanCode,
3848 keyEntry.metaState, keyEntry.repeatCount,
3849 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003850 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003851 ensureEventTraced(keyEntry);
3852 mTracer->traceEventDispatch(*dispatchEntry, *keyEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003853 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
3856
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003857 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003858 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003859 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3860 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003861 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003862 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003863 status = publishMotionEvent(*connection, *dispatchEntry);
Siarhei Vishniakoub0058742024-07-01 16:42:49 -07003864 if (status == BAD_VALUE) {
3865 logDispatchStateLocked();
3866 LOG(FATAL) << "Publisher failed for " << motionEntry;
3867 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003868 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003869 ensureEventTraced(motionEntry);
3870 mTracer->traceEventDispatch(*dispatchEntry, *motionEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003871 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 break;
3873 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003874
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003875 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003876 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003877 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003879 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003880 break;
3881 }
3882
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003883 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3884 const TouchModeEntry& touchModeEntry =
3885 static_cast<const TouchModeEntry&>(eventEntry);
3886 status = connection->inputPublisher
3887 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3888 touchModeEntry.inTouchMode);
3889
3890 break;
3891 }
3892
Prabir Pradhan99987712020-11-10 18:43:05 -08003893 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3894 const auto& captureEntry =
3895 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
Hiroki Sato25040232024-02-22 17:21:22 +09003896 status =
3897 connection->inputPublisher
3898 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3899 captureEntry.pointerCaptureRequest.isEnable());
Prabir Pradhan99987712020-11-10 18:43:05 -08003900 break;
3901 }
3902
arthurhungb89ccb02020-12-30 16:19:01 +08003903 case EventEntry::Type::DRAG: {
3904 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3905 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3906 dragEntry.id, dragEntry.x,
3907 dragEntry.y,
3908 dragEntry.isExiting);
3909 break;
3910 }
3911
Chris Yef59a2f42020-10-16 12:55:26 -07003912 case EventEntry::Type::DEVICE_RESET:
3913 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003914 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003915 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003916 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 }
3919
3920 // Check the result.
3921 if (status) {
3922 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003923 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 "This is unexpected because the wait queue is empty, so the pipe "
3926 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003927 "event to it, status=%s(%d)",
3928 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3929 status);
Harry Cutts33476232023-01-30 19:57:29 +00003930 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 } else {
3932 // Pipe is full and we are waiting for the app to finish process some events
3933 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003934 if (DEBUG_DISPATCH_CYCLE) {
3935 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3936 "waiting for the application to catch up",
3937 connection->getInputChannelName().c_str());
3938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 }
3940 } else {
3941 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003942 "status=%s(%d)",
3943 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3944 status);
Harry Cutts33476232023-01-30 19:57:29 +00003945 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947 return;
3948 }
3949
3950 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003951 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3952 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3953 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003954 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003955 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003956 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003957 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003958 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 }
3960}
3961
chaviw09c8d2d2020-08-24 15:48:26 -07003962std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3963 size_t size;
3964 switch (event.type) {
3965 case VerifiedInputEvent::Type::KEY: {
3966 size = sizeof(VerifiedKeyEvent);
3967 break;
3968 }
3969 case VerifiedInputEvent::Type::MOTION: {
3970 size = sizeof(VerifiedMotionEvent);
3971 break;
3972 }
3973 }
3974 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3975 return mHmacKeyManager.sign(start, size);
3976}
3977
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003978const std::array<uint8_t, 32> InputDispatcher::getSignature(
3979 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003980 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003981 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003982 // Only sign events up and down events as the purely move events
3983 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003984 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003985 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003986
3987 VerifiedMotionEvent verifiedEvent =
3988 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3989 verifiedEvent.actionMasked = actionMasked;
3990 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3991 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003992}
3993
3994const std::array<uint8_t, 32> InputDispatcher::getSignature(
3995 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3996 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3997 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003998 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003999}
4000
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004002 const std::shared_ptr<Connection>& connection,
4003 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004004 if (DEBUG_DISPATCH_CYCLE) {
4005 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
4006 connection->getInputChannelName().c_str(), seq, toString(handled));
4007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004009 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 return;
4011 }
4012
4013 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00004014 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
4015 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
4016 };
4017 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018}
4019
4020void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004021 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004024 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
4025 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027
4028 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004029 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00004030 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004031 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00004032 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
4034 // The connection appears to be unrecoverably broken.
4035 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004036 if (connection->status == Connection::Status::NORMAL) {
4037 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
4039 if (notify) {
4040 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00004041 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
4042 connection->getInputChannelName().c_str());
4043
4044 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004045 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004046 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00004047 };
4048 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 }
4050 }
4051}
4052
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004053void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004054 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004055 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004056 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 }
4058}
4059
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004060void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064}
4065
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004066int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
4067 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004068 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004069 if (connection == nullptr) {
4070 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
4071 connectionToken.get(), events);
4072 return 0; // remove the callback
4073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004075 bool notify;
4076 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
4077 if (!(events & ALOOPER_EVENT_INPUT)) {
4078 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
4079 "events=0x%x",
4080 connection->getInputChannelName().c_str(), events);
4081 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004084 nsecs_t currentTime = now();
4085 bool gotOne = false;
4086 status_t status = OK;
4087 for (;;) {
4088 Result<InputPublisher::ConsumerResponse> result =
4089 connection->inputPublisher.receiveConsumerResponse();
4090 if (!result.ok()) {
4091 status = result.error().code();
4092 break;
4093 }
4094
4095 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
4096 const InputPublisher::Finished& finish =
4097 std::get<InputPublisher::Finished>(*result);
4098 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
4099 finish.consumeTime);
4100 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004101 if (shouldReportMetricsForConnection(*connection)) {
4102 const InputPublisher::Timeline& timeline =
4103 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004104 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
4105 connection->getToken(),
4106 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004107 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004108 }
4109 gotOne = true;
4110 }
4111 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004112 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004113 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 return 1;
4115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 }
4117
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004118 notify = status != DEAD_OBJECT || !connection->monitor;
4119 if (notify) {
4120 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4121 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4122 status);
4123 }
4124 } else {
4125 // Monitor channels are never explicitly unregistered.
4126 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004127 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004128 notify = !connection->monitor && stillHaveWindowHandle;
4129 if (notify) {
4130 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4131 connection->getInputChannelName().c_str(), events);
4132 }
4133 }
4134
4135 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004136 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004137 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138}
4139
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004142 // Cancel windows (i.e. non-monitors).
4143 // A channel must have at least one window to receive any input. If a window was removed, the
4144 // event streams directed to the window will already have been canceled during window removal.
4145 // So there is no need to generate cancellations for connections without any windows.
4146 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4147 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4148 // through a non-touched window if there are more than one window for an input channel.
4149 if (cancelPointers) {
4150 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4151 if (options.displayId.has_value() && options.displayId != displayId) {
4152 continue;
4153 }
4154 for (const auto& touchedWindow : touchState.windows) {
4155 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4156 }
4157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004159 // Follow up by generating cancellations for all windows, because we don't explicitly track
4160 // the windows that have an ongoing focus event stream.
4161 if (cancelNonPointers) {
4162 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4163 for (const auto& windowHandle : handles) {
4164 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4165 }
4166 }
4167 }
4168
4169 // Cancel monitors.
4170 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171}
4172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004174 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004175 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004176 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004177 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4178 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004179 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004180 }
4181}
4182
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004183void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4184 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4185 const std::shared_ptr<Connection>& connection) {
4186 if (windowHandle == nullptr) {
4187 LOG(FATAL) << __func__ << ": Window handle must not be null";
4188 }
4189 if (connection) {
4190 // The connection can be optionally provided to avoid multiple lookups.
4191 if (windowHandle->getToken() != connection->getToken()) {
4192 LOG(FATAL) << __func__
4193 << ": Wrong connection provided for window: " << windowHandle->getName();
4194 }
4195 }
4196
4197 std::shared_ptr<Connection> resolvedConnection =
4198 connection ? connection : getConnectionLocked(windowHandle->getToken());
4199 if (!resolvedConnection) {
4200 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4201 return;
4202 }
4203 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4204}
4205
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004207 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4208 const sp<WindowInfoHandle>& window) {
4209 if (!connection->monitor && window == nullptr) {
4210 LOG(FATAL) << __func__
4211 << ": Cannot send event to non-monitor channel without a window - channel: "
4212 << connection->getInputChannelName();
4213 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004214 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 return;
4216 }
4217
4218 nsecs_t currentTime = now();
4219
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004220 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004221 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004223 if (cancelationEvents.empty()) {
4224 return;
4225 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004226
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004227 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4228 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004229 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004230 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004231 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004232 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233
Arthur Hungb3307ee2021-10-14 10:57:37 +00004234 std::string reason = std::string("reason=").append(options.reason);
4235 android_log_event_list(LOGTAG_INPUT_CANCEL)
4236 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4237
hongzuo liu95785e22022-09-06 02:51:35 +00004238 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004239 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004240 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004241 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004242
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004243 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004244 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004245 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004246
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004247 switch (cancelationEventEntry->type) {
4248 case EventEntry::Type::KEY: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004249 if (mTracer) {
4250 static_cast<KeyEntry&>(*cancelationEventEntry).traceTracker =
4251 mTracer->traceDerivedEvent(*cancelationEventEntry,
4252 *options.traceTracker);
4253 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004254 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004255 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004256 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4257 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004258 } else {
4259 targets.emplace_back(fallbackTarget);
4260 }
4261 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004262 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004264 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004265 if (mTracer) {
4266 static_cast<MotionEntry&>(*cancelationEventEntry).traceTracker =
4267 mTracer->traceDerivedEvent(*cancelationEventEntry,
4268 *options.traceTracker);
4269 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004270 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004271 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004272 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004273 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004274 pointerIndex++) {
4275 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4276 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004277 if (mDragState && mDragState->dragWindow->getToken() == token &&
4278 pointerIds.test(mDragState->pointerId)) {
4279 LOG(INFO) << __func__
4280 << ": Canceling drag and drop because the pointers for the drag "
4281 "window are being canceled.";
4282 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4283 mDragState.reset();
4284 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004285 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4286 ftl::Flags<InputTarget::Flags>(), pointerIds,
4287 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004288 } else {
4289 targets.emplace_back(fallbackTarget);
4290 const auto it = mDisplayInfos.find(motionEntry.displayId);
4291 if (it != mDisplayInfos.end()) {
4292 targets.back().displayTransform = it->second.transform;
4293 targets.back().setDefaultPointerTransform(it->second.transform);
4294 }
4295 }
4296 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004299 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004300 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004301 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4302 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004303 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004304 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004305 break;
4306 }
Chris Yef59a2f42020-10-16 12:55:26 -07004307 case EventEntry::Type::DEVICE_RESET:
4308 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004309 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004310 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004311 break;
4312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004315 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004316 if (mTracer) {
4317 mTracer->dispatchToTargetHint(*options.traceTracker, targets[0]);
4318 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004319 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004321
hongzuo liu95785e22022-09-06 02:51:35 +00004322 // If the outbound queue was previously empty, start the dispatch cycle going.
4323 if (wasEmpty && !connection->outboundQueue.empty()) {
4324 startDispatchCycleLocked(currentTime, connection);
4325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326}
4327
Svet Ganov5d3bc372020-01-26 23:11:07 -08004328void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004329 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004330 ftl::Flags<InputTarget::Flags> targetFlags,
4331 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004332 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004333 return;
4334 }
4335
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004336 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004337 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004338
4339 if (downEvents.empty()) {
4340 return;
4341 }
4342
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004343 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004344 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4345 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004346 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004347
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004348 const auto [_, touchedWindowState, displayId] =
4349 findTouchStateWindowAndDisplayLocked(connection->getToken());
4350 if (touchedWindowState == nullptr) {
4351 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4352 }
4353 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004354
hongzuo liu95785e22022-09-06 02:51:35 +00004355 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004356 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004357 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004358 switch (downEventEntry->type) {
4359 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004360 if (mTracer) {
4361 static_cast<MotionEntry&>(*downEventEntry).traceTracker =
4362 mTracer->traceDerivedEvent(*downEventEntry, *traceTracker);
4363 }
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004364 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4365 if (windowHandle != nullptr) {
4366 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004367 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004368 pointerIndex++) {
4369 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4370 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004371 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4372 targetFlags, pointerIds, motionEntry.downTime,
4373 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004374 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004375 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004376 const auto it = mDisplayInfos.find(motionEntry.displayId);
4377 if (it != mDisplayInfos.end()) {
4378 targets.back().displayTransform = it->second.transform;
4379 targets.back().setDefaultPointerTransform(it->second.transform);
4380 }
4381 }
4382 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004383 break;
4384 }
4385
4386 case EventEntry::Type::KEY:
4387 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004388 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004389 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004390 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004391 case EventEntry::Type::SENSOR:
4392 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004393 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004394 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004395 break;
4396 }
4397 }
4398
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004399 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004400 if (mTracer) {
4401 mTracer->dispatchToTargetHint(*traceTracker, targets[0]);
4402 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004403 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004404 }
4405
hongzuo liu95785e22022-09-06 02:51:35 +00004406 // If the outbound queue was previously empty, start the dispatch cycle going.
4407 if (wasEmpty && !connection->outboundQueue.empty()) {
4408 startDispatchCycleLocked(downTime, connection);
4409 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004410}
4411
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004412std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004413 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4414 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004415 const auto& [action, pointerProperties, pointerCoords] =
4416 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4417 /*historySize=*/0, originalMotionEntry.pointerProperties,
4418 originalMotionEntry.pointerCoords, pointerIds);
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004419 if (pointerIds.count() != pointerCoords.size()) {
4420 // TODO(b/329107108): Determine why some IDs in pointerIds were not in originalMotionEntry.
4421 // This is bad. We are missing some of the pointers that we expected to deliver.
4422 // Most likely this indicates that we received an ACTION_MOVE events that has
4423 // different pointer ids than we expected based on the previous ACTION_DOWN
4424 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4425 // in this way.
Siarhei Vishniakoued89cbb2023-10-13 10:42:44 -07004426 ALOGW("Dropping split motion event because the pointer count is %zu but "
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004427 "we expected there to be %zu pointers. This probably means we received "
4428 "a broken sequence of pointer ids from the input device: %s",
4429 pointerCoords.size(), pointerIds.count(),
4430 originalMotionEntry.getDescription().c_str());
4431 return nullptr;
4432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004434 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4435 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004436 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4437 logDispatchStateLocked();
4438 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4439 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4440 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004441 }
4442
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004443 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004444 ATRACE_NAME_IF(ATRACE_ENABLED(),
4445 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4446 ").",
4447 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004448 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004449 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4450 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451 originalMotionEntry.deviceId, originalMotionEntry.source,
4452 originalMotionEntry.displayId,
4453 originalMotionEntry.policyFlags, action,
4454 originalMotionEntry.actionButton,
4455 originalMotionEntry.flags, originalMotionEntry.metaState,
4456 originalMotionEntry.buttonState,
4457 originalMotionEntry.classification,
4458 originalMotionEntry.edgeFlags,
4459 originalMotionEntry.xPrecision,
4460 originalMotionEntry.yPrecision,
4461 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004462 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004463 pointerProperties, pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +00004464 if (mTracer) {
4465 splitMotionEntry->traceTracker =
4466 mTracer->traceDerivedEvent(*splitMotionEntry, *originalMotionEntry.traceTracker);
4467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 return splitMotionEntry;
4470}
4471
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004472void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4473 std::scoped_lock _l(mLock);
Liana Kazanova5b8217b2024-07-18 17:44:51 +00004474 // Reset key repeating in case a keyboard device was added or removed or something.
4475 resetKeyRepeatLocked();
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004476 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4477}
4478
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004479void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004480 ALOGD_IF(debugInboundEventDetails(),
4481 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
Linnan Li13bf76a2024-05-05 19:18:02 +08004482 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, action=%s, flags=0x%x, "
4483 "keyCode=%s, scanCode=0x%x, metaState=0x%x, "
Prabir Pradhan96282b02023-02-24 22:36:17 +00004484 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004485 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004486 args.displayId.toString().c_str(), args.policyFlags,
4487 KeyEvent::actionToString(args.action), args.flags, KeyEvent::getLabel(args.keyCode),
4488 args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004489 Result<void> keyCheck = validateKeyEvent(args.action);
4490 if (!keyCheck.ok()) {
4491 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 return;
4493 }
4494
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004495 uint32_t policyFlags = args.policyFlags;
4496 int32_t flags = args.flags;
4497 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004498 // InputDispatcher tracks and generates key repeats on behalf of
4499 // whatever notifies it, so repeatCount should always be set to 0
4500 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4502 policyFlags |= POLICY_FLAG_VIRTUAL;
4503 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 if (policyFlags & POLICY_FLAG_FUNCTION) {
4506 metaState |= AMETA_FUNCTION_ON;
4507 }
4508
4509 policyFlags |= POLICY_FLAG_TRUSTED;
4510
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004511 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004513 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4514 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4515 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516
Michael Wright2b3c3302018-03-02 17:19:13 +00004517 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004518 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004519 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4520 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004521 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
Antonio Kantekf16f2832021-09-28 04:39:20 +00004524 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 { // acquire lock
4526 mLock.lock();
4527
Asmita Poddar2808d7e2024-09-12 13:15:38 +00004528 if (input_flags::keyboard_repeat_keys() && !mConfig.keyRepeatEnabled) {
4529 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
4530 }
4531
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 if (shouldSendKeyToInputFilterLocked(args)) {
4533 mLock.unlock();
4534
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004535 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004536 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 return; // event was consumed by the filter
4538 }
4539
4540 mLock.lock();
4541 }
4542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004543 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004544 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4545 args.deviceId, args.source, args.displayId, policyFlags,
4546 args.action, flags, keyCode, args.scanCode, metaState,
4547 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004548 if (mTracer) {
4549 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Asmita Poddar92135902024-09-30 16:10:59 +00004552 if (mPerDeviceInputLatencyMetricsFlag) {
jioana099e19a2024-09-19 15:37:34 +00004553 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4554 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
4555 !mInputFilterEnabled) {
4556 mLatencyTracker.trackNotifyKey(args);
4557 }
4558 }
4559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 mLock.unlock();
4562 } // release lock
4563
4564 if (needWake) {
4565 mLooper->wake();
4566 }
4567}
4568
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004569bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 return mInputFilterEnabled;
4571}
4572
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004573void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004574 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004575 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08004576 "displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004577 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004578 "xCursorPosition=%f, yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004579 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004580 args.displayId.toString().c_str(), args.policyFlags,
4581 MotionEvent::actionToString(args.action).c_str(), args.actionButton, args.flags,
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004582 args.metaState, args.buttonState, args.xCursorPosition, args.yCursorPosition,
4583 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004584 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004585 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4586 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004587 i, args.pointerProperties[i].id,
4588 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4589 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4590 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4591 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4592 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4593 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4594 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4595 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4596 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4597 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004600
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004601 Result<void> motionCheck =
4602 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4603 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004604 if (!motionCheck.ok()) {
4605 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4606 return;
4607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004609 if (DEBUG_VERIFY_EVENTS) {
4610 auto [it, _] =
4611 mVerifiersByDisplay.try_emplace(args.displayId,
Linnan Li13bf76a2024-05-05 19:18:02 +08004612 StringPrintf("display %s",
4613 args.displayId.toString().c_str()));
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004614 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004615 it->second.processMovement(args.deviceId, args.source, args.action,
4616 args.getPointerCount(), args.pointerProperties.data(),
4617 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004618 if (!result.ok()) {
4619 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4620 }
4621 }
4622
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004623 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004625
4626 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004627 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4628 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004629 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4630 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633
Antonio Kantekf16f2832021-09-28 04:39:20 +00004634 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 { // acquire lock
4636 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004637 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4638 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4639 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004640 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004641 if (touchStateIt != mTouchStatesByDisplay.end()) {
4642 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004643 if (touchState.hasTouchingPointers(args.deviceId) ||
4644 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004645 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4646 }
4647 }
4648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649
4650 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004651 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004652 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004653 displayTransform = it->second.transform;
4654 }
4655
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 mLock.unlock();
4657
4658 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004659 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4660 args.action, args.actionButton, args.flags, args.edgeFlags,
4661 args.metaState, args.buttonState, args.classification,
4662 displayTransform, args.xPrecision, args.yPrecision,
4663 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004664 args.downTime, args.eventTime, args.getPointerCount(),
4665 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666
4667 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004668 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 return; // event was consumed by the filter
4670 }
4671
4672 mLock.lock();
4673 }
4674
4675 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004676 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004677 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4678 args.deviceId, args.source, args.displayId,
4679 policyFlags, args.action, args.actionButton,
4680 args.flags, args.metaState, args.buttonState,
4681 args.classification, args.edgeFlags, args.xPrecision,
4682 args.yPrecision, args.xCursorPosition,
4683 args.yCursorPosition, args.downTime,
4684 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004685 if (mTracer) {
4686 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004689 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4690 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004691 !mInputFilterEnabled) {
jioana099e19a2024-09-19 15:37:34 +00004692 mLatencyTracker.trackNotifyMotion(args);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004693 }
4694
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004695 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 mLock.unlock();
4697 } // release lock
4698
4699 if (needWake) {
4700 mLooper->wake();
4701 }
4702}
4703
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004704void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004705 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004706 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4707 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004708 args.id, args.eventTime, args.deviceId, args.source,
4709 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004710 }
Chris Yef59a2f42020-10-16 12:55:26 -07004711
Antonio Kantekf16f2832021-09-28 04:39:20 +00004712 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004713 { // acquire lock
4714 mLock.lock();
4715
4716 // Just enqueue a new sensor event.
4717 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004718 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4719 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4720 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004721
4722 needWake = enqueueInboundEventLocked(std::move(newEntry));
4723 mLock.unlock();
4724 } // release lock
4725
4726 if (needWake) {
4727 mLooper->wake();
4728 }
4729}
4730
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004731void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004732 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004733 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4734 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004735 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004736 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004737}
4738
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004739bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004740 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741}
4742
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004743void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004744 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004745 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4746 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004747 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004750 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004752 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753}
4754
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004755void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004756 // TODO(b/308677868) Remove device reset from the InputListener interface
Prabir Pradhan65613802023-02-22 23:36:58 +00004757 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004758 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4759 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761
Antonio Kantekf16f2832021-09-28 04:39:20 +00004762 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004764 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004766 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004767 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004768 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004769
4770 for (auto& [_, verifier] : mVerifiersByDisplay) {
4771 verifier.resetDevice(args.deviceId);
4772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 } // release lock
4774
4775 if (needWake) {
4776 mLooper->wake();
4777 }
4778}
4779
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004780void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004781 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004782 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
Hiroki Sato25040232024-02-22 17:21:22 +09004783 args.request.isEnable() ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004784 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004785
Antonio Kantekf16f2832021-09-28 04:39:20 +00004786 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004787 { // acquire lock
4788 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004789 auto entry =
4790 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004791 needWake = enqueueInboundEventLocked(std::move(entry));
4792 } // release lock
4793
4794 if (needWake) {
4795 mLooper->wake();
4796 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004797}
4798
Prabir Pradhan5735a322022-04-11 17:23:34 +00004799InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004800 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004801 InputEventInjectionSync syncMode,
4802 std::chrono::milliseconds timeout,
4803 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004804 Result<void> eventValidation = validateInputEvent(*event);
4805 if (!eventValidation.ok()) {
4806 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4807 return InputEventInjectionResult::FAILED;
4808 }
4809
Prabir Pradhan65613802023-02-22 23:36:58 +00004810 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004811 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4812 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4813 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4814 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004815 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004816 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
Prabir Pradhan5735a322022-04-11 17:23:34 +00004818 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004820 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004821 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4822 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4823 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4824 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4825 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004826 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004827 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004828 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004829 }
4830
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004831 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4832 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004834 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004836 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004837 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004838 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004839 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004840 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4841 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4842 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004843 int32_t keyCode = incomingKey.getKeyCode();
4844 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004845 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004846 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004847 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4848 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4849 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004851 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4852 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004853 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004854
4855 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4856 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004857 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004858 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4859 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4860 std::to_string(t.duration().count()).c_str());
4861 }
4862 }
4863
4864 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004865 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004866 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4867 incomingKey.getEventTime(), resolvedDeviceId,
4868 incomingKey.getSource(), incomingKey.getDisplayId(),
4869 policyFlags, action, flags, keyCode,
4870 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004871 incomingKey.getRepeatCount(),
4872 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004873 if (mTracer) {
4874 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004876 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004877 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004880 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004881 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004882 const bool isPointerEvent =
4883 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4884 // If a pointer event has no displayId specified, inject it to the default display.
Linnan Li13bf76a2024-05-05 19:18:02 +08004885 const ui::LogicalDisplayId displayId =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004886 isPointerEvent && (event->getDisplayId() == ui::LogicalDisplayId::INVALID)
4887 ? ui::LogicalDisplayId::DEFAULT
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004888 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004889 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004890
4891 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004892 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004893 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004894 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4895 motionEvent.getAction(), eventTime,
4896 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004897 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4898 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4899 std::to_string(t.duration().count()).c_str());
4900 }
4901 }
4902
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004903 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4904 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4905 }
4906
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004907 mLock.lock();
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004908
Siarhei Vishniakoueb75bc82024-06-04 13:05:45 -07004909 {
4910 // Verify all injected streams, whether the injection is coming from apps or from
4911 // input filter. Print an error if the stream becomes inconsistent with this event.
4912 // An inconsistent injected event sent could cause a crash in the later stages of
4913 // dispatching pipeline.
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004914 auto [it, _] =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004915 mInputFilterVerifiersByDisplay.try_emplace(displayId,
4916 std::string("Injection on ") +
4917 displayId.toString());
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004918 InputVerifier& verifier = it->second;
4919
4920 Result<void> result =
4921 verifier.processMovement(resolvedDeviceId, motionEvent.getSource(),
4922 motionEvent.getAction(),
4923 motionEvent.getPointerCount(),
4924 motionEvent.getPointerProperties(),
4925 motionEvent.getSamplePointerCoords(), flags);
4926 if (!result.ok()) {
4927 logDispatchStateLocked();
4928 LOG(ERROR) << "Inconsistent event: " << motionEvent
4929 << ", reason: " << result.error();
Siarhei Vishniakou9d0d65e2024-08-02 12:10:05 -07004930 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4931 mLock.unlock();
4932 return InputEventInjectionResult::FAILED;
4933 }
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004934 }
4935 }
4936
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004937 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004938 const size_t pointerCount = motionEvent.getPointerCount();
4939 const std::vector<PointerProperties>
4940 pointerProperties(motionEvent.getPointerProperties(),
4941 motionEvent.getPointerProperties() + pointerCount);
4942
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004943 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004944 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004945 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4946 *sampleEventTimes, resolvedDeviceId,
4947 motionEvent.getSource(), displayId, policyFlags,
4948 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004949 motionEvent.getActionButton(), flags,
4950 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004951 motionEvent.getButtonState(),
4952 motionEvent.getClassification(),
4953 motionEvent.getEdgeFlags(),
4954 motionEvent.getXPrecision(),
4955 motionEvent.getYPrecision(),
4956 motionEvent.getRawXCursorPosition(),
4957 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004958 motionEvent.getDownTime(), pointerProperties,
4959 std::vector<PointerCoords>(samplePointerCoords,
4960 samplePointerCoords +
4961 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004962 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004963 if (mTracer) {
4964 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4965 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004966 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004967 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004968 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004969 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004970 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004971 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4972 resolvedDeviceId, motionEvent.getSource(), displayId,
4973 policyFlags, motionEvent.getAction(),
4974 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004975 motionEvent.getMetaState(), motionEvent.getButtonState(),
4976 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4977 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4978 motionEvent.getRawXCursorPosition(),
4979 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4980 pointerProperties,
4981 std::vector<PointerCoords>(samplePointerCoords,
4982 samplePointerCoords +
4983 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004984 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4985 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004986 if (mTracer) {
4987 nextInjectedEntry->traceTracker =
4988 mTracer->traceInboundEvent(*nextInjectedEntry);
4989 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004990 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004991 }
4992 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004996 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004997 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 }
4999
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005001 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08005002 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005003 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08005004 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005005 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005006 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 }
5008
5009 mLock.unlock();
5010
5011 if (needWake) {
5012 mLooper->wake();
5013 }
5014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005015 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005017 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005019 if (syncMode == InputEventInjectionSync::NONE) {
5020 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 } else {
5022 for (;;) {
5023 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005024 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 break;
5026 }
5027
5028 nsecs_t remainingTimeout = endTime - now();
5029 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005030 if (DEBUG_INJECTION) {
5031 ALOGD("injectInputEvent - Timed out waiting for injection result "
5032 "to become available.");
5033 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005034 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 break;
5036 }
5037
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005038 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005041 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
5042 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005044 if (DEBUG_INJECTION) {
5045 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
5046 injectionState->pendingForegroundDispatches);
5047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 nsecs_t remainingTimeout = endTime - now();
5049 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005050 if (DEBUG_INJECTION) {
5051 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
5052 "dispatches to finish.");
5053 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005054 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 break;
5056 }
5057
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005058 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 }
5060 }
5061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 } // release lock
5063
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005064 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005065 LOG(INFO) << "injectInputEvent - Finished with result "
5066 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068
5069 return injectionResult;
5070}
5071
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005072std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05005073 std::array<uint8_t, 32> calculatedHmac;
5074 std::unique_ptr<VerifiedInputEvent> result;
5075 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005076 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05005077 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
5078 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
5079 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005080 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05005081 break;
5082 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005083 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05005084 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
5085 VerifiedMotionEvent verifiedMotionEvent =
5086 verifiedMotionEventFromMotionEvent(motionEvent);
5087 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005088 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05005089 break;
5090 }
5091 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08005092 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05005093 return nullptr;
5094 }
5095 }
5096 if (calculatedHmac == INVALID_HMAC) {
5097 return nullptr;
5098 }
tyiu1573a672023-02-21 22:38:32 +00005099 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05005100 return nullptr;
5101 }
5102 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005103}
5104
Prabir Pradhan24047542023-11-02 17:14:59 +00005105void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005106 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005107 if (!entry.injectionState) {
5108 // Not an injected event.
5109 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005111
5112 InjectionState& injectionState = *entry.injectionState;
5113 if (DEBUG_INJECTION) {
5114 LOG(INFO) << "Setting input event injection result to "
5115 << ftl::enum_string(injectionResult);
5116 }
5117
5118 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
5119 // Log the outcome since the injector did not wait for the injection result.
5120 switch (injectionResult) {
5121 case InputEventInjectionResult::SUCCEEDED:
5122 ALOGV("Asynchronous input event injection succeeded.");
5123 break;
5124 case InputEventInjectionResult::TARGET_MISMATCH:
5125 ALOGV("Asynchronous input event injection target mismatch.");
5126 break;
5127 case InputEventInjectionResult::FAILED:
5128 ALOGW("Asynchronous input event injection failed.");
5129 break;
5130 case InputEventInjectionResult::TIMED_OUT:
5131 ALOGW("Asynchronous input event injection timed out.");
5132 break;
5133 case InputEventInjectionResult::PENDING:
5134 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5135 break;
5136 }
5137 }
5138
5139 injectionState.injectionResult = injectionResult;
5140 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141}
5142
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005143void InputDispatcher::transformMotionEntryForInjectionLocked(
5144 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005145 // Input injection works in the logical display coordinate space, but the input pipeline works
5146 // display space, so we need to transform the injected events accordingly.
5147 const auto it = mDisplayInfos.find(entry.displayId);
5148 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005149 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005150
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005151 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5152 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5153 const vec2 cursor =
5154 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5155 {entry.xCursorPosition, entry.yCursorPosition});
5156 entry.xCursorPosition = cursor.x;
5157 entry.yCursorPosition = cursor.y;
5158 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005159 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005160 entry.pointerCoords[i] =
Prabir Pradhan9a53b552024-06-04 02:59:40 +00005161 MotionEvent::calculateTransformedCoords(entry.source, entry.flags,
5162 transformToDisplay, entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005163 }
5164}
5165
Prabir Pradhan24047542023-11-02 17:14:59 +00005166void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005167 if (entry.injectionState) {
5168 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 }
5170}
5171
Prabir Pradhan24047542023-11-02 17:14:59 +00005172void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005173 if (entry.injectionState) {
5174 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005176 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005177 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
5179 }
5180}
5181
chaviw98318de2021-05-19 16:45:23 -05005182const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005183 ui::LogicalDisplayId displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005184 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005185 auto it = mWindowHandlesByDisplay.find(displayId);
5186 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005187}
5188
chaviw98318de2021-05-19 16:45:23 -05005189sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005190 const sp<IBinder>& windowHandleToken, std::optional<ui::LogicalDisplayId> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005191 if (windowHandleToken == nullptr) {
5192 return nullptr;
5193 }
5194
Prabir Pradhan16463382023-10-12 23:03:19 +00005195 if (!displayId) {
5196 // Look through all displays.
Linnan Li13bf76a2024-05-05 19:18:02 +08005197 for (const auto& [_, windowHandles] : mWindowHandlesByDisplay) {
Prabir Pradhan16463382023-10-12 23:03:19 +00005198 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5199 if (windowHandle->getToken() == windowHandleToken) {
5200 return windowHandle;
5201 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005204 return nullptr;
5205 }
5206
Prabir Pradhan16463382023-10-12 23:03:19 +00005207 // Only look through the requested display.
5208 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005209 if (windowHandle->getToken() == windowHandleToken) {
5210 return windowHandle;
5211 }
5212 }
5213 return nullptr;
5214}
5215
chaviw98318de2021-05-19 16:45:23 -05005216sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5217 const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08005218 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005219 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005220 if (handle->getId() == windowHandle->getId() &&
5221 handle->getToken() == windowHandle->getToken()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005222 if (windowHandle->getInfo()->displayId != displayId) {
5223 ALOGE("Found window %s in display %s"
5224 ", but it should belong to display %s",
5225 windowHandle->getName().c_str(), displayId.toString().c_str(),
5226 windowHandle->getInfo()->displayId.toString().c_str());
Mady Mellor017bcd12020-06-23 19:12:00 +00005227 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005228 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 }
5231 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005232 return nullptr;
5233}
5234
Linnan Li13bf76a2024-05-05 19:18:02 +08005235sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(
5236 ui::LogicalDisplayId displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005237 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5238 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239}
5240
Linnan Li13bf76a2024-05-05 19:18:02 +08005241ui::Transform InputDispatcher::getTransformLocked(ui::LogicalDisplayId displayId) const {
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005242 auto displayInfoIt = mDisplayInfos.find(displayId);
5243 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5244 : kIdentityTransform;
5245}
5246
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005247bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5248 const MotionEntry& motionEntry) const {
5249 const WindowInfo& info = *window->getInfo();
5250
5251 // Skip spy window targets that are not valid for targeted injection.
5252 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005253 return false;
5254 }
5255
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005256 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5257 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5258 return false;
5259 }
5260
5261 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5262 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5263 window->getName().c_str());
5264 return false;
5265 }
5266
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005267 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005268 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005269 ALOGW("Not sending touch to %s because there's no corresponding connection",
5270 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005271 return false;
5272 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005273
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005274 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005275 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005276 return false;
5277 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005278
5279 // Drop events that can't be trusted due to occlusion
5280 const auto [x, y] = resolveTouchedPosition(motionEntry);
5281 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5282 if (!isTouchTrustedLocked(occlusionInfo)) {
5283 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005284 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005285 for (const auto& log : occlusionInfo.debugInfo) {
5286 ALOGD("%s", log.c_str());
5287 }
5288 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005289 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5290 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005291 return false;
5292 }
5293
5294 // Drop touch events if requested by input feature
5295 if (shouldDropInput(motionEntry, window)) {
5296 return false;
5297 }
5298
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005299 // Ignore touches if stylus is down anywhere on screen
5300 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5301 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5302 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5303 return false;
5304 }
5305
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005306 return true;
5307}
5308
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005309void InputDispatcher::updateWindowHandlesForDisplayLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005310 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5311 ui::LogicalDisplayId displayId) {
chaviw98318de2021-05-19 16:45:23 -05005312 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005313 // Remove all handles on a display if there are no windows left.
5314 mWindowHandlesByDisplay.erase(displayId);
5315 return;
5316 }
5317
5318 // Since we compare the pointer of input window handles across window updates, we need
5319 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005320 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5321 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5322 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005323 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005324 }
5325
chaviw98318de2021-05-19 16:45:23 -05005326 std::vector<sp<WindowInfoHandle>> newHandles;
5327 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005328 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005329 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005330 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005331 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005332 const bool canReceiveInput =
5333 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5334 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005335 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005336 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005337 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005338 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005339 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005340 }
5341
5342 if (info->displayId != displayId) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005343 ALOGE("Window %s updated by wrong display %s, should belong to display %s",
5344 handle->getName().c_str(), displayId.toString().c_str(),
5345 info->displayId.toString().c_str());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005346 continue;
5347 }
5348
Robert Carredd13602020-04-13 17:24:34 -07005349 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
Linnan Li13bf76a2024-05-05 19:18:02 +08005350 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005351 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005352 oldHandle->updateFrom(handle);
5353 newHandles.push_back(oldHandle);
5354 } else {
5355 newHandles.push_back(handle);
5356 }
5357 }
5358
5359 // Insert or replace
5360 mWindowHandlesByDisplay[displayId] = newHandles;
5361}
5362
Arthur Hungb92218b2018-08-14 12:00:21 +08005363/**
5364 * Called from InputManagerService, update window handle list by displayId that can receive input.
5365 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5366 * If set an empty list, remove all handles from the specific display.
5367 * For focused handle, check if need to change and send a cancel event to previous one.
5368 * For removed handle, check if need to send a cancel event if already in touch.
5369 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005370void InputDispatcher::setInputWindowsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005371 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5372 ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005373 if (DEBUG_FOCUS) {
5374 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005375 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005376 windowList += iwh->getName() + " ";
5377 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005378 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005379 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005380 ScopedSyntheticEventTracer traceContext(mTracer);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381
Prabir Pradhand65552b2021-10-07 11:23:50 -07005382 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005383 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005384 const WindowInfo& info = *window->getInfo();
5385
5386 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005387 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005388 if (noInputWindow && window->getToken() != nullptr) {
5389 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5390 window->getName().c_str());
5391 window->releaseChannel();
5392 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005393
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005394 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005395 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5396 !info.inputConfig.test(
5397 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005398 "%s has feature SPY, but is not a trusted overlay.",
5399 window->getName().c_str());
5400
Prabir Pradhand65552b2021-10-07 11:23:50 -07005401 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005402 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5403 !info.inputConfig.test(
5404 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005405 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5406 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005407 }
5408
Arthur Hung72d8dc32020-03-28 00:48:39 +00005409 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005410 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005411 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412
chaviw98318de2021-05-19 16:45:23 -05005413 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005414
chaviw98318de2021-05-19 16:45:23 -05005415 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005416
Vishnu Nairc519ff72021-01-21 08:23:08 -08005417 std::optional<FocusResolver::FocusChanges> changes =
5418 mFocusResolver.setInputWindows(displayId, windowHandles);
5419 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005420 onFocusChangedLocked(*changes, traceContext.getTracker(), removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422
Linnan Li72352222024-04-12 18:55:57 +08005423 if (const auto& it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
5424 TouchState& state = it->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005425 for (size_t i = 0; i < state.windows.size();) {
5426 TouchedWindow& touchedWindow = state.windows[i];
Linnan Li72352222024-04-12 18:55:57 +08005427 if (getWindowHandleLocked(touchedWindow.windowHandle) != nullptr) {
5428 i++;
5429 continue;
5430 }
5431 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5432 << " in display %" << displayId;
5433 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5434 "touched window was removed", traceContext.getTracker());
5435 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5436 // Since we are about to drop the touch, cancel the events for the wallpaper as
5437 // well.
5438 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5439 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5440 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5441 for (const DeviceId deviceId : touchedWindow.getTouchingDeviceIds()) {
5442 if (const auto& ww = state.getWallpaperWindow(deviceId); ww != nullptr) {
5443 options.deviceId = deviceId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005444 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 }
Linnan Li72352222024-04-12 18:55:57 +08005448 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 }
arthurhungb89ccb02020-12-30 16:19:01 +08005450
arthurhung6d4bed92021-03-17 11:59:33 +08005451 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005452 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005453 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005454 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005455 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005456 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5457 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005458 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005459 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005460 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005461
Siarhei Vishniakoub711e652024-08-12 12:00:28 -07005462 // Check if the hovering should stop because the window is no longer eligible to receive it
5463 // (for example, if the touchable region changed)
5464 if (const auto& it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
5465 TouchState& state = it->second;
5466 for (TouchedWindow& touchedWindow : state.windows) {
5467 std::vector<DeviceId> erasedDevices = touchedWindow.eraseHoveringPointersIf(
5468 [this, displayId, &touchedWindow](const PointerProperties& properties, float x,
5469 float y) REQUIRES(mLock) {
5470 const bool isStylus = properties.toolType == ToolType::STYLUS;
5471 const ui::Transform displayTransform = getTransformLocked(displayId);
5472 const bool stillAcceptsTouch =
5473 windowAcceptsTouchAt(*touchedWindow.windowHandle->getInfo(),
5474 displayId, x, y, isStylus, displayTransform);
5475 return !stillAcceptsTouch;
5476 });
5477
5478 for (DeviceId deviceId : erasedDevices) {
5479 CancelationOptions options(CancelationOptions::Mode::CANCEL_HOVER_EVENTS,
5480 "WindowInfo changed",
5481 traceContext.getTracker());
5482 options.deviceId = deviceId;
5483 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5484 }
5485 }
5486 }
5487
Arthur Hung72d8dc32020-03-28 00:48:39 +00005488 // Release information for windows that are no longer present.
5489 // This ensures that unused input channels are released promptly.
5490 // Otherwise, they might stick around until the window handle is destroyed
5491 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005492 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005493 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005494 if (DEBUG_FOCUS) {
5495 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005496 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005497 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005498 }
chaviw291d88a2019-02-14 10:33:58 -08005499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500}
5501
5502void InputDispatcher::setFocusedApplication(
Linnan Li13bf76a2024-05-05 19:18:02 +08005503 ui::LogicalDisplayId displayId,
5504 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005505 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005506 ALOGD("setFocusedApplication displayId=%s %s", displayId.toString().c_str(),
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005507 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5508 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005509 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005510 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005511 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 } // release lock
5513
5514 // Wake up poll loop since it may need to make new input dispatching choices.
5515 mLooper->wake();
5516}
5517
Vishnu Nair599f1412021-06-21 10:39:58 -07005518void InputDispatcher::setFocusedApplicationLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005519 ui::LogicalDisplayId displayId,
5520 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Vishnu Nair599f1412021-06-21 10:39:58 -07005521 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5522 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5523
5524 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5525 return; // This application is already focused. No need to wake up or change anything.
5526 }
5527
5528 // Set the new application handle.
5529 if (inputApplicationHandle != nullptr) {
5530 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5531 } else {
5532 mFocusedApplicationHandlesByDisplay.erase(displayId);
5533 }
5534
5535 // No matter what the old focused application was, stop waiting on it because it is
5536 // no longer focused.
5537 resetNoFocusedWindowTimeoutLocked();
5538}
5539
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005540void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5541 if (interval.count() < 0) {
5542 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5543 }
5544 std::scoped_lock _l(mLock);
5545 mMinTimeBetweenUserActivityPokes = interval;
5546}
5547
Tiger Huang721e26f2018-07-24 22:26:19 +08005548/**
5549 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5550 * the display not specified.
5551 *
5552 * We track any unreleased events for each window. If a window loses the ability to receive the
5553 * released event, we will send a cancel event to it. So when the focused display is changed, we
5554 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5555 * display. The display-specified events won't be affected.
5556 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005557void InputDispatcher::setFocusedDisplay(ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005558 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005559 ALOGD("setFocusedDisplay displayId=%s", displayId.toString().c_str());
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005560 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005561 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005562 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005563 ScopedSyntheticEventTracer traceContext(mTracer);
Tiger Huang721e26f2018-07-24 22:26:19 +08005564
5565 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005566 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005567 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005568 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005569 const auto windowHandle =
5570 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5571 if (windowHandle == nullptr) {
5572 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005573 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005574 CancelationOptions
5575 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005576 "The display which contains this window no longer has focus.",
5577 traceContext.getTracker());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005578 options.displayId = ui::LogicalDisplayId::INVALID;
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005579 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005580 }
5581 mFocusedDisplayId = displayId;
Arpit Singhb65e2bd2024-06-03 09:48:16 +00005582 // Enqueue a command to run outside the lock to tell the policy that the focused display
5583 // changed.
5584 auto command = [this]() REQUIRES(mLock) {
5585 scoped_unlock unlock(mLock);
5586 mPolicy.notifyFocusedDisplayChanged(mFocusedDisplayId);
5587 };
5588 postCommandLocked(std::move(command));
Tiger Huang721e26f2018-07-24 22:26:19 +08005589
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00005590 // Only a window on the focused display can have Pointer Capture, so disable the active
5591 // Pointer Capture session if there is one, since the focused display changed.
5592 disablePointerCaptureForcedLocked();
5593
Chris Ye3c2d6f52020-08-09 10:39:48 -07005594 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005595 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005596 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005597
Vishnu Nairad321cd2020-08-20 16:40:21 -07005598 if (newFocusedWindowToken == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005599 ALOGW("Focused display #%s does not have a focused window.",
5600 displayId.toString().c_str());
Vishnu Nairc519ff72021-01-21 08:23:08 -08005601 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005602 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005603 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005604 }
5605 }
5606 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005607 } // release lock
5608
5609 // Wake up poll loop since it may need to make new input dispatching choices.
5610 mLooper->wake();
5611}
5612
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005614 if (DEBUG_FOCUS) {
5615 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
5618 bool changed;
5619 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005620 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621
5622 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5623 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005624 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 }
5626
5627 if (mDispatchEnabled && !enabled) {
5628 resetAndDropEverythingLocked("dispatcher is being disabled");
5629 }
5630
5631 mDispatchEnabled = enabled;
5632 mDispatchFrozen = frozen;
5633 changed = true;
5634 } else {
5635 changed = false;
5636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 } // release lock
5638
5639 if (changed) {
5640 // Wake up poll loop since it may need to make new input dispatching choices.
5641 mLooper->wake();
5642 }
5643}
5644
5645void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005646 if (DEBUG_FOCUS) {
5647 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649
5650 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005651 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652
5653 if (mInputFilterEnabled == enabled) {
5654 return;
5655 }
5656
5657 mInputFilterEnabled = enabled;
5658 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5659 } // release lock
5660
5661 // Wake up poll loop since there might be work to do to drop everything.
5662 mLooper->wake();
5663}
5664
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005665bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Linnan Li13bf76a2024-05-05 19:18:02 +08005666 bool hasPermission, ui::LogicalDisplayId displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005667 bool needWake = false;
5668 {
5669 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005670 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005671 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08005672 "hasPermission=%s, target displayId=%s, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005673 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08005674 toString(hasPermission), displayId.toString().c_str(),
Antonio Kantek15beb512022-06-13 22:35:41 +00005675 mTouchModePerDisplay.count(displayId) == 0
5676 ? "not set"
5677 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5678
Antonio Kantek15beb512022-06-13 22:35:41 +00005679 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5680 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005681 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005682 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005683 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005684 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5685 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005686 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005687 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005688 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005689 return false;
5690 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005691 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005692 mTouchModePerDisplay[displayId] = inTouchMode;
5693 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5694 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005695 needWake = enqueueInboundEventLocked(std::move(entry));
5696 } // release lock
5697
5698 if (needWake) {
5699 mLooper->wake();
5700 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005701 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005702}
5703
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005704bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005705 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5706 if (focusedToken == nullptr) {
5707 return false;
5708 }
5709 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5710 return isWindowOwnedBy(windowHandle, pid, uid);
5711}
5712
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005713bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005714 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5715 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5716 const sp<WindowInfoHandle> windowHandle =
5717 getWindowHandleLocked(connectionToken);
5718 return isWindowOwnedBy(windowHandle, pid, uid);
5719 }) != mInteractionConnectionTokens.end();
5720}
5721
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005722void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5723 if (opacity < 0 || opacity > 1) {
5724 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5725 return;
5726 }
5727
5728 std::scoped_lock lock(mLock);
5729 mMaximumObscuringOpacityForTouch = opacity;
5730}
5731
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005732std::tuple<TouchState*, TouchedWindow*, ui::LogicalDisplayId>
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005733InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005734 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5735 for (TouchedWindow& w : state.windows) {
5736 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005737 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005738 }
5739 }
5740 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005741 return std::make_tuple(nullptr, nullptr, ui::LogicalDisplayId::DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005742}
5743
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005744std::tuple<const TouchState*, const TouchedWindow*, ui::LogicalDisplayId>
5745InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) const {
5746 return const_cast<InputDispatcher*>(this)->findTouchStateWindowAndDisplayLocked(token);
5747}
5748
5749bool InputDispatcher::windowHasTouchingPointersLocked(const sp<WindowInfoHandle>& windowHandle,
5750 DeviceId deviceId) const {
5751 const auto& [touchState, touchedWindow, _] =
5752 findTouchStateWindowAndDisplayLocked(windowHandle->getToken());
5753 if (touchState == nullptr) {
5754 // No touching pointers at all
5755 return false;
5756 }
5757 return touchState->hasTouchingPointers(deviceId);
5758}
5759
Prabir Pradhan367f3432024-02-13 23:05:58 +00005760bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5761 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005762 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005763 if (DEBUG_FOCUS) {
5764 ALOGD("Trivial transfer to same window.");
5765 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005766 return true;
5767 }
5768
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005770 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771
Arthur Hungabbb9d82021-09-01 14:52:30 +00005772 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005773 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005774
Arthur Hungabbb9d82021-09-01 14:52:30 +00005775 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005776 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 return false;
5778 }
Linnan Li72352222024-04-12 18:55:57 +08005779 std::set<DeviceId> deviceIds = touchedWindow->getTouchingDeviceIds();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005780 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005781 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5782 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005783 return false;
5784 }
Linnan Li72352222024-04-12 18:55:57 +08005785 const DeviceId deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005786
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005787 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5788 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5789 if (!toWindowHandle) {
5790 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005791 return false;
5792 }
5793
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005794 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005795 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005796 touchedWindow->windowHandle->getName().c_str(),
5797 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 }
5799
Arthur Hungabbb9d82021-09-01 14:52:30 +00005800 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005801 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005802 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005803 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804
Arthur Hungabbb9d82021-09-01 14:52:30 +00005805 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005806 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005807 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005808 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005809 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005810 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005811 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005812 // Transferring touch focus using this API should not effect the focused window.
5813 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005814 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005815 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816
Arthur Hungabbb9d82021-09-01 14:52:30 +00005817 // Store the dragging window.
5818 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005819 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005820 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5821 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005822 return false;
5823 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005824 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005825 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005826 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 }
5828
Arthur Hungabbb9d82021-09-01 14:52:30 +00005829 // Synthesize cancel for old window and down for new window.
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005830 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005831 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5832 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005833 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005834 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005835 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005836 "transferring touch from this window to another window",
5837 traceContext.getTracker());
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005838 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005839
5840 // Check if the wallpaper window should deliver the corresponding event.
5841 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005842 *state, deviceId, pointers, traceContext.getTracker());
Linnan Li72352222024-04-12 18:55:57 +08005843
5844 // Because new window may have a wallpaper window, it will merge input state from it
5845 // parent window, after this the firstNewPointerIdx in input state will be reset, then
5846 // it will cause new move event be thought inconsistent, so we should synthesize the
5847 // down event after it reset.
5848 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5849 newTargetFlags,
5850 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852 } // release lock
5853
5854 // Wake up poll loop since it may need to make new input dispatching choices.
5855 mLooper->wake();
5856 return true;
5857}
5858
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005859/**
5860 * Get the touched foreground window on the given display.
5861 * Return null if there are no windows touched on that display, or if more than one foreground
5862 * window is being touched.
5863 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005864sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(
5865 ui::LogicalDisplayId displayId) const {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005866 auto stateIt = mTouchStatesByDisplay.find(displayId);
5867 if (stateIt == mTouchStatesByDisplay.end()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005868 ALOGI("No touch state on display %s", displayId.toString().c_str());
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005869 return nullptr;
5870 }
5871
5872 const TouchState& state = stateIt->second;
5873 sp<WindowInfoHandle> touchedForegroundWindow;
5874 // If multiple foreground windows are touched, return nullptr
5875 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005876 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005877 if (touchedForegroundWindow != nullptr) {
5878 ALOGI("Two or more foreground windows: %s and %s",
5879 touchedForegroundWindow->getName().c_str(),
5880 window.windowHandle->getName().c_str());
5881 return nullptr;
5882 }
5883 touchedForegroundWindow = window.windowHandle;
5884 }
5885 }
5886 return touchedForegroundWindow;
5887}
5888
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005889// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005890bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
Linnan Li13bf76a2024-05-05 19:18:02 +08005891 ui::LogicalDisplayId displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005892 sp<IBinder> fromToken;
5893 { // acquire lock
5894 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005895 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005896 if (toWindowHandle == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005897 ALOGW("Could not find window associated with token=%p on display %s",
5898 destChannelToken.get(), displayId.toString().c_str());
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005899 return false;
5900 }
5901
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005902 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5903 if (from == nullptr) {
5904 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5905 return false;
5906 }
5907
5908 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005909 } // release lock
5910
Prabir Pradhan367f3432024-02-13 23:05:58 +00005911 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005912}
5913
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005915 if (DEBUG_FOCUS) {
5916 ALOGD("Resetting and dropping all events (%s).", reason);
5917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005919 ScopedSyntheticEventTracer traceContext(mTracer);
5920 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason,
5921 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922 synthesizeCancelationEventsForAllConnectionsLocked(options);
5923
5924 resetKeyRepeatLocked();
5925 releasePendingEventLocked();
5926 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005927 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005929 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005930 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931}
5932
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005933void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005934 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935 dumpDispatchStateLocked(dump);
5936
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005937 std::istringstream stream(dump);
5938 std::string line;
5939
5940 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005941 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 }
5943}
5944
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005945std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005946 std::string dump;
5947
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005948 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
Hiroki Sato25040232024-02-22 17:21:22 +09005949 toString(mCurrentPointerCaptureRequest.isEnable()));
Prabir Pradhan99987712020-11-10 18:43:05 -08005950
5951 std::string windowName = "None";
5952 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005953 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005954 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5955 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5956 : "token has capture without window";
5957 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005958 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005959
5960 return dump;
5961}
5962
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005963void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005964 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5965 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5966 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Linnan Li13bf76a2024-05-05 19:18:02 +08005967 dump += StringPrintf(INDENT "FocusedDisplayId: %s\n", mFocusedDisplayId.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968
Tiger Huang721e26f2018-07-24 22:26:19 +08005969 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5970 dump += StringPrintf(INDENT "FocusedApplications:\n");
5971 for (auto& it : mFocusedApplicationHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005972 const ui::LogicalDisplayId displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005973 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005974 const std::chrono::duration timeout =
5975 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Linnan Li13bf76a2024-05-05 19:18:02 +08005976 dump += StringPrintf(INDENT2 "displayId=%s, name='%s', dispatchingTimeout=%" PRId64
5977 "ms\n",
5978 displayId.toString().c_str(), applicationHandle->getName().c_str(),
5979 millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005982 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005984
Vishnu Nairc519ff72021-01-21 08:23:08 -08005985 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005986 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005988 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005989 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005990 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005991 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
Linnan Li13bf76a2024-05-05 19:18:02 +08005992 dump += INDENT2 + displayId.toString() + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005993 }
5994 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005995 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005996 }
5997
arthurhung6d4bed92021-03-17 11:59:33 +08005998 if (mDragState) {
5999 dump += StringPrintf(INDENT "DragState:\n");
6000 mDragState->dump(dump, INDENT2);
6001 }
6002
Arthur Hungb92218b2018-08-14 12:00:21 +08006003 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006004 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006005 dump += StringPrintf(INDENT "Display: %s\n", displayId.toString().c_str());
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006006 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
6007 const auto& displayInfo = it->second;
6008 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
6009 displayInfo.logicalHeight);
6010 displayInfo.transform.dump(dump, "transform", INDENT4);
6011 } else {
6012 dump += INDENT2 "No DisplayInfo found!\n";
6013 }
6014
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006015 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08006016 dump += INDENT2 "Windows:\n";
6017 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006018 dump += StringPrintf(INDENT3 "%zu: %s", i,
6019 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08006020 }
6021 } else {
6022 dump += INDENT2 "Windows: <none>\n";
6023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 }
6025 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08006026 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 }
6028
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006029 if (!mGlobalMonitorsByDisplay.empty()) {
6030 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006031 dump += StringPrintf(INDENT "Global monitors on display %s:\n",
6032 displayId.toString().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00006033 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006036 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 }
6038
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006039 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040
6041 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006042 if (!mRecentQueue.empty()) {
6043 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00006044 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006045 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006046 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006047 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 }
6049 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006050 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 }
6052
6053 // Dump event currently being dispatched.
6054 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006055 dump += INDENT "PendingEvent:\n";
6056 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006057 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006058 dump += StringPrintf(", age=%" PRId64 "ms\n",
6059 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006061 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062 }
6063
6064 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006065 if (!mInboundQueue.empty()) {
6066 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00006067 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006068 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006069 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006070 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
6072 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006073 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074 }
6075
Prabir Pradhancef936d2021-07-21 16:17:52 +00006076 if (!mCommandQueue.empty()) {
6077 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
6078 } else {
6079 dump += INDENT "CommandQueue: <empty>\n";
6080 }
6081
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006082 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006083 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006084 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006085 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006086 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006087 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006088 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006089 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006090 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006092 if (!connection->outboundQueue.empty()) {
6093 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
6094 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006095 dump += dumpQueue(connection->outboundQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 }
6097
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006098 if (!connection->waitQueue.empty()) {
6099 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
6100 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006101 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006103 std::string inputStateDump = streamableToString(connection->inputState);
6104 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006105 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006106 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108 }
6109 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006110 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
6112
Antonio Kantek15beb512022-06-13 22:35:41 +00006113 if (!mTouchModePerDisplay.empty()) {
6114 dump += INDENT "TouchModePerDisplay:\n";
6115 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006116 dump += StringPrintf(INDENT2 "Display: %s TouchMode: %s\n",
6117 displayId.toString().c_str(), std::to_string(touchMode).c_str());
Antonio Kantek15beb512022-06-13 22:35:41 +00006118 }
6119 } else {
6120 dump += INDENT "TouchModePerDisplay: <none>\n";
6121 }
6122
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006123 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006124 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
6125 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
6126 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00006127 dump += mLatencyTracker.dump(INDENT2);
jioana24878b52024-09-10 10:13:27 +00006128 dump += mInputEventTimelineProcessor->dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00006129 dump += INDENT "InputTracer: ";
6130 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131}
6132
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07006133void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00006134 const size_t numMonitors = monitors.size();
6135 for (size_t i = 0; i < numMonitors; i++) {
6136 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006137 const std::shared_ptr<Connection>& connection = monitor.connection;
6138 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00006139 dump += "\n";
6140 }
6141}
6142
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006143class LooperEventCallback : public LooperCallback {
6144public:
6145 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
6146 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
6147
6148private:
6149 std::function<int(int events)> mCallback;
6150};
6151
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006152Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006153 if (DEBUG_CHANNEL_CREATION) {
6154 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
6155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006157 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006158 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006159 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006160
6161 if (result) {
6162 return base::Error(result) << "Failed to open input channel pair with name " << name;
6163 }
6164
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006166 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006167 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006168 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006169 std::shared_ptr<Connection> connection =
6170 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
6171 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006173 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
6174 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006175 ALOGE("Created a new connection, but the token %p is already known", token.get());
6176 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006177
6178 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6179 this, std::placeholders::_1, token);
6180
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006181 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006182 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 } // release lock
6184
6185 // Wake the looper because some connections have changed.
6186 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006187 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188}
6189
Linnan Li13bf76a2024-05-05 19:18:02 +08006190Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
6191 ui::LogicalDisplayId displayId, const std::string& name, gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006192 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006193 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006194 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006195 if (result) {
6196 return base::Error(result) << "Failed to open input channel pair with name " << name;
6197 }
6198
Michael Wright3dd60e22019-03-27 22:06:44 +00006199 { // acquire lock
6200 std::scoped_lock _l(mLock);
6201
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07006202 if (displayId < ui::LogicalDisplayId::DEFAULT) {
Garfield Tan15601662020-09-22 15:32:38 -07006203 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6204 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006205 }
6206
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006207 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006208 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006209 std::shared_ptr<Connection> connection =
6210 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6211 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006212
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006213 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6214 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006215 ALOGE("Created a new connection, but the token %p is already known", token.get());
6216 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006217
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006218 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6219 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006220
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006221 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006222
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006223 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006224 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006225 }
Garfield Tan15601662020-09-22 15:32:38 -07006226
Michael Wright3dd60e22019-03-27 22:06:44 +00006227 // Wake the looper because some connections have changed.
6228 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006229 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006230}
6231
Garfield Tan15601662020-09-22 15:32:38 -07006232status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006234 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235
Harry Cutts33476232023-01-30 19:57:29 +00006236 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 if (status) {
6238 return status;
6239 }
6240 } // release lock
6241
6242 // Wake the poll loop because removing the connection may have changed the current
6243 // synchronization state.
6244 mLooper->wake();
6245 return OK;
6246}
6247
Garfield Tan15601662020-09-22 15:32:38 -07006248status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6249 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006250 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006251 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006252 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 return BAD_VALUE;
6254 }
6255
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006256 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006257
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006259 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 }
6261
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006262 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263
6264 nsecs_t currentTime = now();
6265 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6266
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006267 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 return OK;
6269}
6270
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006271void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006272 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6273 auto& [displayId, monitors] = *it;
6274 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006275 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006276 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006277
Michael Wright3dd60e22019-03-27 22:06:44 +00006278 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006279 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006280 } else {
6281 ++it;
6282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 }
6284}
6285
Michael Wright3dd60e22019-03-27 22:06:44 +00006286status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006287 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006288 return pilferPointersLocked(token);
6289}
Michael Wright3dd60e22019-03-27 22:06:44 +00006290
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006291status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006292 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6293 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006294 LOG(WARNING)
6295 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006296 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006297 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006298
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006299 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006300 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006301 LOG(WARNING)
6302 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6303 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006304 return BAD_VALUE;
6305 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006306 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006307 if (deviceIds.empty()) {
6308 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006309 return BAD_VALUE;
6310 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006311
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006312 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006313 for (const DeviceId deviceId : deviceIds) {
6314 TouchState& state = *statePtr;
6315 TouchedWindow& window = *windowPtr;
6316 // Send cancel events to all the input channels we're stealing from.
6317 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006318 "input channel stole pointer stream", traceContext.getTracker());
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006319 options.deviceId = deviceId;
6320 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006321 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6322 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006323 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006324
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006325 std::string canceledWindows;
6326 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006327 if (w.windowHandle->getToken() != token) {
6328 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006329 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006330 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006331 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006332 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006333 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006334 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006335 << " is stealing input gesture for device " << deviceId << " from "
6336 << canceledWindows;
6337
6338 // Prevent the gesture from being sent to any other windows.
6339 // This only blocks relevant pointers to be sent to other windows
6340 window.addPilferingPointers(deviceId, pointerIds);
6341
6342 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006343 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006344 return OK;
6345}
6346
Prabir Pradhan99987712020-11-10 18:43:05 -08006347void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6348 { // acquire lock
6349 std::scoped_lock _l(mLock);
6350 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006351 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006352 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6353 windowHandle != nullptr ? windowHandle->getName().c_str()
6354 : "token without window");
6355 }
6356
Vishnu Nairc519ff72021-01-21 08:23:08 -08006357 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006358 if (focusedToken != windowToken) {
6359 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6360 enabled ? "enable" : "disable");
6361 return;
6362 }
6363
Hiroki Sato25040232024-02-22 17:21:22 +09006364 if (enabled == mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006365 ALOGW("Ignoring request to %s Pointer Capture: "
6366 "window has %s requested pointer capture.",
6367 enabled ? "enable" : "disable", enabled ? "already" : "not");
6368 return;
6369 }
6370
Christine Franksb768bb42021-11-29 12:11:31 -08006371 if (enabled) {
6372 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6373 mIneligibleDisplaysForPointerCapture.end(),
6374 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6375 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6376 return;
6377 }
6378 }
6379
Hiroki Sato25040232024-02-22 17:21:22 +09006380 setPointerCaptureLocked(enabled ? windowToken : nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08006381 } // release lock
6382
6383 // Wake the thread to process command entries.
6384 mLooper->wake();
6385}
6386
Linnan Li13bf76a2024-05-05 19:18:02 +08006387void InputDispatcher::setDisplayEligibilityForPointerCapture(ui::LogicalDisplayId displayId,
6388 bool isEligible) {
Christine Franksb768bb42021-11-29 12:11:31 -08006389 { // acquire lock
6390 std::scoped_lock _l(mLock);
6391 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6392 if (!isEligible) {
6393 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6394 }
6395 } // release lock
6396}
6397
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006398std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006399 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006400 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006401 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006402 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006403 }
6404 }
6405 }
6406 return std::nullopt;
6407}
6408
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006409std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6410 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006411 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006412 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006413 }
6414
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006415 for (const auto& [token, connection] : mConnectionsByToken) {
6416 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006417 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006418 }
6419 }
Robert Carr4e670e52018-08-15 13:26:12 -07006420
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006421 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006422}
6423
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006424std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006425 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006426 if (connection == nullptr) {
6427 return "<nullptr>";
6428 }
6429 return connection->getInputChannelName();
6430}
6431
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006432void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006433 mAnrTracker.eraseToken(connection->getToken());
6434 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006435}
6436
Prabir Pradhancef936d2021-07-21 16:17:52 +00006437void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006438 const std::shared_ptr<Connection>& connection,
6439 uint32_t seq, bool handled,
6440 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006441 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006442 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006443
6444 { // Start critical section
6445 auto dispatchEntryIt =
6446 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6447 [seq](auto& e) { return e->seq == seq; });
6448 if (dispatchEntryIt == connection->waitQueue.end()) {
6449 return;
6450 }
6451
6452 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6453
6454 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6455 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006456 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006457 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6458 }
6459 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006460 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006461 dispatchEntry.deliveryTime, consumeTime, finishTime);
6462 }
6463
6464 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006465 fallbackKeyEntry =
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006466 afterKeyEventLockedInterruptable(connection, &dispatchEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006467 }
6468 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006469
6470 // Dequeue the event and start the next cycle.
6471 // Because the lock might have been released, it is possible that the
6472 // contents of the wait queue to have been drained, so we need to double-check
6473 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006474 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6475 [seq](auto& e) { return e->seq == seq; });
6476 if (entryIt != connection->waitQueue.end()) {
6477 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6478 connection->waitQueue.erase(entryIt);
6479
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006480 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006481 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6482 if (!connection->responsive) {
6483 connection->responsive = isConnectionResponsive(*connection);
6484 if (connection->responsive) {
6485 // The connection was unresponsive, and now it's responsive.
6486 processConnectionResponsiveLocked(*connection);
6487 }
6488 }
6489 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006490 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006491 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6492 // Only dispatch fallbacks if there is a window for the connection.
6493 if (windowHandle != nullptr) {
6494 const auto inputTarget =
6495 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6496 dispatchEntry->targetFlags,
6497 fallbackKeyEntry->downTime);
6498 if (inputTarget.has_value()) {
6499 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6500 *inputTarget);
6501 }
6502 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006503 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006504 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006505 }
6506
6507 // Start the next dispatch cycle for this connection.
6508 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509}
6510
Prabir Pradhancef936d2021-07-21 16:17:52 +00006511void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6512 const sp<IBinder>& newToken) {
6513 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6514 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006515 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006516 };
6517 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518}
6519
Prabir Pradhancef936d2021-07-21 16:17:52 +00006520void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6521 auto command = [this, token, x, y]() REQUIRES(mLock) {
6522 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006523 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006524 };
6525 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006526}
6527
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006528void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006529 if (connection == nullptr) {
6530 LOG_ALWAYS_FATAL("Caller must check for nullness");
6531 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006532 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6533 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006534 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006535 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006536 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006537 return;
6538 }
6539 /**
6540 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6541 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6542 * has changed. This could cause newer entries to time out before the already dispatched
6543 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6544 * processes the events linearly. So providing information about the oldest entry seems to be
6545 * most useful.
6546 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006547 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6548 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006549 std::string reason =
6550 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006551 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006552 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006553 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006554 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006555 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006556
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006557 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6558
6559 // Stop waking up for events on this connection, it is already unresponsive
6560 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006561}
6562
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006563void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6564 std::string reason =
6565 StringPrintf("%s does not have a focused window", application->getName().c_str());
6566 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006567
Yabin Cui8eb9c552023-06-08 18:05:07 +00006568 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006569 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006570 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006571 };
6572 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006573}
6574
chaviw98318de2021-05-19 16:45:23 -05006575void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006576 const std::string& reason) {
6577 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6578 updateLastAnrStateLocked(windowLabel, reason);
6579}
6580
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006581void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6582 const std::string& reason) {
6583 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006584 updateLastAnrStateLocked(windowLabel, reason);
6585}
6586
6587void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6588 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006590 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 struct tm tm;
6592 localtime_r(&t, &tm);
6593 char timestr[64];
6594 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006595 mLastAnrState.clear();
6596 mLastAnrState += INDENT "ANR:\n";
6597 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006598 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6599 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006600 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006601}
6602
Prabir Pradhancef936d2021-07-21 16:17:52 +00006603void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006604 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006605 const KeyEvent event = createKeyEvent(entry);
6606 nsecs_t delay = 0;
6607 { // release lock
6608 scoped_unlock unlock(mLock);
6609 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006610 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006611 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6612 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6613 std::to_string(t.duration().count()).c_str());
6614 }
6615 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616
6617 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006618 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006619 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006620 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006621 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006622 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006623 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625}
6626
Prabir Pradhancef936d2021-07-21 16:17:52 +00006627void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006628 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006629 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006630 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006631 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006632 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006633 };
6634 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006635}
6636
Prabir Pradhanedd96402022-02-15 01:46:16 -08006637void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006638 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006639 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006640 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006641 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006642 };
6643 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006644}
6645
6646/**
6647 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6648 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6649 * command entry to the command queue.
6650 */
6651void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6652 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006653 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006654 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006655 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006656 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006657 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006658 pid = findMonitorPidByTokenLocked(connectionToken);
6659 } else {
6660 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006661 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006662 reason.c_str());
6663 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6664 if (handle != nullptr) {
6665 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006666 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006667 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006668 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006669}
6670
6671/**
6672 * Tell the policy that a connection has become responsive so that it can stop ANR.
6673 */
6674void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006675 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006676 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006677 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006678 pid = findMonitorPidByTokenLocked(connectionToken);
6679 } else {
6680 // The connection is a window
6681 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6682 if (handle != nullptr) {
6683 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006684 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006685 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006686 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006687}
6688
Prabir Pradhan24047542023-11-02 17:14:59 +00006689std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006690 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry, bool handled) {
6691 // The dispatchEntry is currently valid, but it might point to a deleted object after we release
6692 // the lock. For simplicity, make copies of the data of interest here and assume that
6693 // 'dispatchEntry' is not valid after this section.
6694 // Hold a strong reference to the EventEntry to ensure it's valid for the duration of this
6695 // function, even if the DispatchEntry gets destroyed and releases its share of the ownership.
6696 std::shared_ptr<const EventEntry> eventEntry = dispatchEntry->eventEntry;
6697 const bool hasForegroundTarget = dispatchEntry->hasForegroundTarget();
6698 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(eventEntry));
6699 // To prevent misuse, ensure dispatchEntry is no longer valid.
6700 dispatchEntry = nullptr;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006701 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006702 if (!handled) {
6703 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006704 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006705 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006706 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006708
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006709 // Get the fallback key state.
6710 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006711 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006712 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006713 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006714 connection->inputState.removeFallbackKey(originalKeyCode);
6715 }
6716
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006717 if (handled || !hasForegroundTarget) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006718 // If the application handles the original key for which we previously
6719 // generated a fallback or if the window is not a foreground window,
6720 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006721 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006722 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006723 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6724 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6725 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6726 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6727 keyEntry.policyFlags);
6728 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006729 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006730 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006731
6732 mLock.unlock();
6733
Prabir Pradhana41d2442023-04-20 21:30:40 +00006734 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006735 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6736 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006737 unhandledKeyFallback) {
6738 event = *unhandledKeyFallback;
6739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006740
6741 mLock.lock();
6742
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006743 // Cancel the fallback key, but only if we still have a window for the channel.
6744 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006745 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006746 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6747 if (windowHandle != nullptr) {
6748 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6749 "application handled the original non-fallback key "
6750 "or is no longer a foreground target, "
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006751 "canceling previously dispatched fallback key",
6752 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006753 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006754 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006756 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006757 connection->inputState.removeFallbackKey(originalKeyCode);
6758 }
6759 } else {
6760 // If the application did not handle a non-fallback key, first check
6761 // that we are in a good state to perform unhandled key event processing
6762 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006763 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006764 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006765 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6766 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6767 "since this is not an initial down. "
6768 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6769 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6770 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006771 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006773
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006774 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006775 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6776 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6777 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6778 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6779 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006780 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006781
6782 mLock.unlock();
6783
Prabir Pradhana41d2442023-04-20 21:30:40 +00006784 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006785 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6786 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006787 fb) {
6788 fallback = true;
6789 event = *fb;
6790 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006791
6792 mLock.lock();
6793
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006794 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006795 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006796 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006797 }
6798
6799 // Latch the fallback keycode for this key on an initial down.
6800 // The fallback keycode cannot change at any other point in the lifecycle.
6801 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006802 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006803 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006804 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006805 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006806 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006807 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006808 }
6809
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006810 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006811
6812 // Cancel the fallback key if the policy decides not to send it anymore.
6813 // We will continue to dispatch the key to the policy but we will no
6814 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006815 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6816 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006817 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6818 if (fallback) {
6819 ALOGD("Unhandled key event: Policy requested to send key %d"
6820 "as a fallback for %d, but on the DOWN it had requested "
6821 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006822 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006823 } else {
6824 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6825 "but on the DOWN it had requested to send %d. "
6826 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006827 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006828 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006829 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006830
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006831 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6832 if (windowHandle != nullptr) {
6833 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006834 "canceling fallback, policy no longer desires it",
6835 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006836 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006837 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006838 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006839
6840 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006841 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006842 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006843 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006844 }
6845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006846
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006847 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6848 {
6849 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006850 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006851 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006852 for (const auto& [key, value] : fallbackKeys) {
6853 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006854 }
6855 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6856 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006857 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006858 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006859
6860 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006861 // Return the fallback key that we want dispatched to the channel.
6862 std::unique_ptr<KeyEntry> newEntry =
6863 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6864 event.getEventTime(), event.getDeviceId(),
6865 event.getSource(), event.getDisplayId(),
6866 keyEntry.policyFlags, keyEntry.action,
6867 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6868 *fallbackKeyCode, event.getScanCode(),
6869 event.getMetaState(), event.getRepeatCount(),
6870 event.getDownTime());
Prabir Pradhana67623c2024-02-21 06:57:36 +00006871 if (mTracer) {
6872 newEntry->traceTracker =
6873 mTracer->traceDerivedEvent(*newEntry, *keyEntry.traceTracker);
6874 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006875 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6876 ALOGD("Unhandled key event: Dispatching fallback key. "
6877 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006878 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006879 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006880 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006881 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006882 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6883 ALOGD("Unhandled key event: No fallback key.");
6884 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006885
6886 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006887 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006888 }
6889 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006890 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006891}
6892
Michael Wrightd02c5b62014-02-10 15:10:22 -08006893void InputDispatcher::traceInboundQueueLengthLocked() {
6894 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006895 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896 }
6897}
6898
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006899void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006900 if (ATRACE_ENABLED()) {
6901 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006902 snprintf(counterName, sizeof(counterName), "oq:%s",
6903 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006904 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006905 }
6906}
6907
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006908void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006909 if (ATRACE_ENABLED()) {
6910 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006911 snprintf(counterName, sizeof(counterName), "wq:%s",
6912 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006913 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006914 }
6915}
6916
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006917void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006918 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006919
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006920 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006921 dumpDispatchStateLocked(dump);
6922
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006923 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006924 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006925 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006926 }
6927}
6928
6929void InputDispatcher::monitor() {
6930 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006931 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006932 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006933 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006934}
6935
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006936/**
6937 * Wake up the dispatcher and wait until it processes all events and commands.
6938 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6939 * this method can be safely called from any thread, as long as you've ensured that
6940 * the work you are interested in completing has already been queued.
6941 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006942bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006943 /**
6944 * Timeout should represent the longest possible time that a device might spend processing
6945 * events and commands.
6946 */
6947 constexpr std::chrono::duration TIMEOUT = 100ms;
6948 std::unique_lock lock(mLock);
6949 mLooper->wake();
6950 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6951 return result == std::cv_status::no_timeout;
6952}
6953
Vishnu Naire798b472020-07-23 13:52:21 -07006954/**
6955 * Sets focus to the window identified by the token. This must be called
6956 * after updating any input window handles.
6957 *
6958 * Params:
6959 * request.token - input channel token used to identify the window that should gain focus.
6960 * request.focusedToken - the token that the caller expects currently to be focused. If the
6961 * specified token does not match the currently focused window, this request will be dropped.
6962 * If the specified focused token matches the currently focused window, the call will succeed.
6963 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6964 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6965 * when requesting the focus change. This determines which request gets
6966 * precedence if there is a focus change request from another source such as pointer down.
6967 */
Vishnu Nair958da932020-08-21 17:12:37 -07006968void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6969 { // acquire lock
6970 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006971 std::optional<FocusResolver::FocusChanges> changes =
Linnan Li13bf76a2024-05-05 19:18:02 +08006972 mFocusResolver.setFocusedWindow(request,
6973 getWindowHandlesLocked(
6974 ui::LogicalDisplayId{request.displayId}));
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006975 ScopedSyntheticEventTracer traceContext(mTracer);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006976 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006977 onFocusChangedLocked(*changes, traceContext.getTracker());
Vishnu Nair958da932020-08-21 17:12:37 -07006978 }
6979 } // release lock
6980 // Wake up poll loop since it may need to make new input dispatching choices.
6981 mLooper->wake();
6982}
6983
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006984void InputDispatcher::onFocusChangedLocked(
6985 const FocusResolver::FocusChanges& changes,
6986 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker,
6987 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006988 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006989 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6990 ? removedFocusedWindowHandle
6991 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6992 if (resolvedWindow == nullptr) {
6993 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006994 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006995 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006996 "focus left window", traceTracker);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006997 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6998 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006999 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08007000 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07007001 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00007002 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07007003 }
7004
Vishnu Nairc519ff72021-01-21 08:23:08 -08007005 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00007006 // If a window has pointer capture, then it must have focus and must be on the top-focused
7007 // display. We need to ensure that this contract is upheld when pointer capture is being
7008 // disabled due to a loss of window focus. If the window loses focus before it loses pointer
7009 // capture, then the window can be in a state where it has pointer capture but not focus,
7010 // violating the contract. Therefore we must dispatch the pointer capture event before the
7011 // focus event. Since focus events are added to the front of the queue (above), we add the
7012 // pointer capture event to the front of the queue after the focus events are added. This
7013 // ensures the pointer capture event ends up at the front.
7014 disablePointerCaptureForcedLocked();
7015
Prabir Pradhancef936d2021-07-21 16:17:52 +00007016 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07007017 }
7018}
Vishnu Nair958da932020-08-21 17:12:37 -07007019
Prabir Pradhan99987712020-11-10 18:43:05 -08007020void InputDispatcher::disablePointerCaptureForcedLocked() {
Hiroki Sato25040232024-02-22 17:21:22 +09007021 if (!mCurrentPointerCaptureRequest.isEnable() && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08007022 return;
7023 }
7024
7025 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
7026
Hiroki Sato25040232024-02-22 17:21:22 +09007027 if (mCurrentPointerCaptureRequest.isEnable()) {
7028 setPointerCaptureLocked(nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08007029 }
7030
7031 if (!mWindowTokenWithPointerCapture) {
7032 // No need to send capture changes because no window has capture.
7033 return;
7034 }
7035
7036 if (mPendingEvent != nullptr) {
7037 // Move the pending event to the front of the queue. This will give the chance
7038 // for the pending event to be dropped if it is a captured event.
7039 mInboundQueue.push_front(mPendingEvent);
7040 mPendingEvent = nullptr;
7041 }
7042
7043 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007044 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08007045 mInboundQueue.push_front(std::move(entry));
7046}
7047
Hiroki Sato25040232024-02-22 17:21:22 +09007048void InputDispatcher::setPointerCaptureLocked(const sp<IBinder>& windowToken) {
7049 mCurrentPointerCaptureRequest.window = windowToken;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00007050 mCurrentPointerCaptureRequest.seq++;
7051 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00007052 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00007053 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00007054 };
7055 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08007056}
7057
Linnan Li13bf76a2024-05-05 19:18:02 +08007058void InputDispatcher::displayRemoved(ui::LogicalDisplayId displayId) {
Vishnu Nair599f1412021-06-21 10:39:58 -07007059 { // acquire lock
7060 std::scoped_lock _l(mLock);
7061 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00007062 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07007063 setFocusedApplicationLocked(displayId, nullptr);
7064 // Call focus resolver to clean up stale requests. This must be called after input windows
7065 // have been removed for the removed display.
7066 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08007067 // Reset pointer capture eligibility, regardless of previous state.
7068 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00007069 // Remove the associated touch mode state.
7070 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07007071 mVerifiersByDisplay.erase(displayId);
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00007072 mInputFilterVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07007073 } // release lock
7074
7075 // Wake up poll loop since it may need to make new input dispatching choices.
7076 mLooper->wake();
7077}
7078
Patrick Williamsd828f302023-04-28 17:52:08 -05007079void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08007080 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
7081 {
7082 // acquire lock
7083 std::scoped_lock _l(mLock);
7084 logDispatchStateLocked();
7085 }
7086 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
7087 result.error().message().c_str());
7088 };
chaviw15fab6f2021-06-07 14:15:52 -05007089 // The listener sends the windows as a flattened array. Separate the windows by display for
7090 // more convenient parsing.
Linnan Li13bf76a2024-05-05 19:18:02 +08007091 std::unordered_map<ui::LogicalDisplayId, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05007092 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05007093 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007094 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
Siarhei Vishniakoua3fe6642024-07-18 11:58:25 -07007095 if (input_flags::split_all_touches()) {
7096 handlesPerDisplay[info.displayId]
7097 .back()
7098 ->editInfo()
7099 ->setInputConfig(android::gui::WindowInfo::InputConfig::PREVENT_SPLITTING,
7100 false);
7101 }
chaviw15fab6f2021-06-07 14:15:52 -05007102 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007103
7104 { // acquire lock
7105 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00007106
7107 // Ensure that we have an entry created for all existing displays so that if a displayId has
7108 // no windows, we can tell that the windows were removed from the display.
7109 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
7110 handlesPerDisplay[displayId];
7111 }
7112
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007113 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05007114 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007115 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
7116 }
7117
7118 for (const auto& [displayId, handles] : handlesPerDisplay) {
7119 setInputWindowsLocked(handles, displayId);
7120 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05007121
7122 if (update.vsyncId < mWindowInfosVsyncId) {
7123 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
7124 ", current update vsync id: %" PRId64,
7125 mWindowInfosVsyncId, update.vsyncId);
7126 }
7127 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007128 }
7129 // Wake up poll loop since it may need to make new input dispatching choices.
7130 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05007131}
7132
Vishnu Nair062a8672021-09-03 16:07:44 -07007133bool InputDispatcher::shouldDropInput(
7134 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007135 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
7136 (windowHandle->getInfo()->inputConfig.test(
7137 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07007138 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007139 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
Linnan Li13bf76a2024-05-05 19:18:02 +08007140 "display %s.",
Vishnu Nair062a8672021-09-03 16:07:44 -07007141 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007142 windowHandle->getInfo()->inputConfig.string().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08007143 windowHandle->getInfo()->displayId.toString().c_str());
Vishnu Nair062a8672021-09-03 16:07:44 -07007144 return true;
7145 }
7146 return false;
7147}
7148
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007149void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05007150 const gui::WindowInfosUpdate& update) {
7151 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007152}
7153
Arthur Hungdfd528e2021-12-08 13:23:04 +00007154void InputDispatcher::cancelCurrentTouch() {
7155 {
7156 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007157 ScopedSyntheticEventTracer traceContext(mTracer);
Arthur Hungdfd528e2021-12-08 13:23:04 +00007158 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00007159 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007160 "cancel current touch", traceContext.getTracker());
Arthur Hungdfd528e2021-12-08 13:23:04 +00007161 synthesizeCancelationEventsForAllConnectionsLocked(options);
7162
7163 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00007164 }
7165 // Wake up poll loop since there might be work to do.
7166 mLooper->wake();
7167}
7168
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007169void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
7170 std::scoped_lock _l(mLock);
7171 mMonitorDispatchingTimeout = timeout;
7172}
7173
Arthur Hungc539dbb2022-12-08 07:45:36 +00007174void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
7175 const sp<WindowInfoHandle>& oldWindowHandle,
7176 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007177 TouchState& state, const MotionEntry& entry,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07007178 std::vector<InputTarget>& targets) const {
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007179 LOG_IF(FATAL, entry.getPointerCount() != 1) << "Entry not eligible for slip: " << entry;
7180 const DeviceId deviceId = entry.deviceId;
7181 const PointerProperties& pointerProperties = entry.pointerProperties[0];
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007182 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00007183 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
7184 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7185 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
7186 newWindowHandle->getInfo()->inputConfig.test(
7187 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7188 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007189 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007190 const sp<WindowInfoHandle> newWallpaper =
7191 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
7192 if (oldWallpaper == newWallpaper) {
7193 return;
7194 }
7195
7196 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08007197 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007198 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007199 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007200 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007201 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007202 }
7203
7204 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007205 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
7206 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00007207 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakoufe346982024-08-07 00:17:19 +00007208 deviceId, pointers, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007209 }
7210}
7211
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007212void InputDispatcher::transferWallpaperTouch(
7213 ftl::Flags<InputTarget::Flags> oldTargetFlags,
7214 ftl::Flags<InputTarget::Flags> newTargetFlags, const sp<WindowInfoHandle> fromWindowHandle,
Linnan Li72352222024-04-12 18:55:57 +08007215 const sp<WindowInfoHandle> toWindowHandle, TouchState& state, DeviceId deviceId,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007216 const std::vector<PointerProperties>& pointers,
7217 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00007218 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7219 fromWindowHandle->getInfo()->inputConfig.test(
7220 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7221 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7222 toWindowHandle->getInfo()->inputConfig.test(
7223 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7224
7225 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007226 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007227 const sp<WindowInfoHandle> newWallpaper =
7228 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
7229 if (oldWallpaper == newWallpaper) {
7230 return;
7231 }
7232
7233 if (oldWallpaper != nullptr) {
7234 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007235 "transferring touch focus to another window", traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007236 state.removeWindowByToken(oldWallpaper->getToken());
7237 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7238 }
7239
7240 if (newWallpaper != nullptr) {
7241 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007242 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7243 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007244 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7245 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007246 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007247 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007248 std::shared_ptr<Connection> wallpaperConnection =
7249 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007250 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007251 std::shared_ptr<Connection> toConnection =
7252 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007253 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7254 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007255 wallpaperFlags, traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007256 }
7257 }
7258}
7259
7260sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7261 const sp<WindowInfoHandle>& windowHandle) const {
7262 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7263 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7264 bool foundWindow = false;
7265 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7266 if (!foundWindow && otherHandle != windowHandle) {
7267 continue;
7268 }
7269 if (windowHandle == otherHandle) {
7270 foundWindow = true;
7271 continue;
7272 }
7273
7274 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7275 return otherHandle;
7276 }
7277 }
7278 return nullptr;
7279}
7280
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007281void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
Asmita Poddar2808d7e2024-09-12 13:15:38 +00007282 std::chrono::nanoseconds delay,
7283 bool keyRepeatEnabled) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007284 std::scoped_lock _l(mLock);
7285
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007286 mConfig.keyRepeatTimeout = timeout.count();
7287 mConfig.keyRepeatDelay = delay.count();
Asmita Poddar2808d7e2024-09-12 13:15:38 +00007288 mConfig.keyRepeatEnabled = keyRepeatEnabled;
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007289}
7290
Linnan Li13bf76a2024-05-05 19:18:02 +08007291bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token,
7292 ui::LogicalDisplayId displayId, DeviceId deviceId,
7293 int32_t pointerId) {
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007294 std::scoped_lock _l(mLock);
7295 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7296 if (touchStateIt == mTouchStatesByDisplay.end()) {
7297 return false;
7298 }
7299 for (const TouchedWindow& window : touchStateIt->second.windows) {
7300 if (window.windowHandle->getToken() == token &&
7301 (window.hasTouchingPointer(deviceId, pointerId) ||
7302 window.hasHoveringPointer(deviceId, pointerId))) {
7303 return true;
7304 }
7305 }
7306 return false;
7307}
7308
Prabir Pradhan04a66422024-03-15 22:45:27 +00007309void InputDispatcher::setInputMethodConnectionIsActive(bool isActive) {
7310 std::scoped_lock _l(mLock);
7311 if (mTracer) {
7312 mTracer->setInputMethodConnectionIsActive(isActive);
7313 }
7314}
7315
Garfield Tane84e6f92019-08-29 17:28:41 -07007316} // namespace android::inputdispatcher