blob: 3c83affcbe77992374a88a5273c683f1f406bba5 [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"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000057#include "trace/ThreadedBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62#define INDENT4 " "
63
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080064using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070065using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080066using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000067using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070069using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050070using android::gui::FocusRequest;
71using android::gui::TouchOcclusionMode;
72using android::gui::WindowInfo;
73using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080074using android::os::InputEventInjectionResult;
75using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000076namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000081
Prabir Pradhandae52792023-12-15 07:36:40 +000082// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
83// flag is enabled. When the flag is changed, tracing will only be available after reboot.
84bool isInputTracingEnabled() {
85 static const std::string buildType = base::GetProperty("ro.build.type", "user");
86 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
87 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
88}
89
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000090// Create the input tracing backend that writes to perfetto from a single thread.
91std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
92 if (!isInputTracingEnabled()) {
93 return nullptr;
94 }
95 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
96 trace::impl::PerfettoBackend());
97}
98
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000099template <class Entry>
100void ensureEventTraced(const Entry& entry) {
101 if (!entry.traceTracker) {
102 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
103 }
104}
105
Prabir Pradhan052fb0b2024-02-23 21:03:12 +0000106// Helper to get a trace tracker from a traced key or motion entry.
107const std::unique_ptr<trace::EventTrackerInterface>& getTraceTracker(const EventEntry& entry) {
108 switch (entry.type) {
109 case EventEntry::Type::MOTION: {
110 const auto& motion = static_cast<const MotionEntry&>(entry);
111 ensureEventTraced(motion);
112 return motion.traceTracker;
113 }
114 case EventEntry::Type::KEY: {
115 const auto& key = static_cast<const KeyEntry&>(entry);
116 ensureEventTraced(key);
117 return key.traceTracker;
118 }
119 default: {
120 const static std::unique_ptr<trace::EventTrackerInterface> kNullTracker;
121 return kNullTracker;
122 }
123 }
124}
125
Prabir Pradhancef936d2021-07-21 16:17:52 +0000126// Temporarily releases a held mutex for the lifetime of the instance.
127// Named to match std::scoped_lock
128class scoped_unlock {
129public:
130 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
131 ~scoped_unlock() { mMutex.lock(); }
132
133private:
134 std::mutex& mMutex;
135};
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Default input dispatching timeout if there is no focused application or paused window
138// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800139const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
140 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
141 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800143// The default minimum time gap between two user activity poke events.
144const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
145
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800146const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148// 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 +0000149constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
150
151// Log a warning when an interception call takes longer than this to process.
152constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153
154// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000155constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
156
Antonio Kantekea47acb2021-12-23 12:41:25 -0800157// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000158constexpr int LOGTAG_INPUT_INTERACTION = 62000;
159constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000160constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000161
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000162const ui::Transform kIdentityTransform;
163
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000164inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 return systemTime(SYSTEM_TIME_MONOTONIC);
166}
167
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700168inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000169 if (binder == nullptr) {
170 return "<null>";
171 }
172 return StringPrintf("%p", binder.get());
173}
174
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000175static std::string uidString(const gui::Uid& uid) {
176 return uid.toString();
177}
178
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 case AKEY_EVENT_ACTION_DOWN:
182 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700185 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700189Result<void> validateKeyEvent(int32_t action) {
190 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191}
192
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800194 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700196 case AMOTION_EVENT_ACTION_UP: {
197 if (pointerCount != 1) {
198 return Error() << "invalid pointer count " << pointerCount;
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 case AMOTION_EVENT_ACTION_HOVER_ENTER:
204 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700205 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
206 if (pointerCount < 1) {
207 return Error() << "invalid pointer count " << pointerCount;
208 }
209 return {};
210 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800211 case AMOTION_EVENT_ACTION_CANCEL:
212 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 case AMOTION_EVENT_ACTION_POINTER_DOWN:
216 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800217 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 if (index < 0) {
219 return Error() << "invalid index " << index << " for "
220 << MotionEvent::actionToString(action);
221 }
222 if (index >= pointerCount) {
223 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
224 }
225 if (pointerCount <= 1) {
226 return Error() << "invalid pointer count " << pointerCount << " for "
227 << MotionEvent::actionToString(action);
228 }
229 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700230 }
231 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
233 if (actionButton == 0) {
234 return Error() << "action button should be nonzero for "
235 << MotionEvent::actionToString(action);
236 }
237 return {};
238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700239 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 }
242}
243
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000244int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500245 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
246}
247
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700248Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
249 const PointerProperties* pointerProperties) {
250 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
251 if (!actionCheck.ok()) {
252 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 }
254 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700255 return Error() << "Motion event has invalid pointer count " << pointerCount
256 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800258 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 for (size_t i = 0; i < pointerCount; i++) {
260 int32_t id = pointerProperties[i].id;
261 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700262 return Error() << "Motion event has invalid pointer id " << id
263 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800265 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700266 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800268 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700270 return {};
271}
272
273Result<void> validateInputEvent(const InputEvent& event) {
274 switch (event.getType()) {
275 case InputEventType::KEY: {
276 const KeyEvent& key = static_cast<const KeyEvent&>(event);
277 const int32_t action = key.getAction();
278 return validateKeyEvent(action);
279 }
280 case InputEventType::MOTION: {
281 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
282 const int32_t action = motion.getAction();
283 const size_t pointerCount = motion.getPointerCount();
284 const PointerProperties* pointerProperties = motion.getPointerProperties();
285 const int32_t actionButton = motion.getActionButton();
286 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
287 }
288 default: {
289 return {};
290 }
291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292}
293
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800294std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
295 std::bitset<MAX_POINTER_ID + 1> pointerIds;
296 for (const PointerProperties& pointer : pointers) {
297 pointerIds.set(pointer.id);
298 }
299 return pointerIds;
300}
301
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000302std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000304 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 }
306
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000307 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 bool first = true;
309 Region::const_iterator cur = region.begin();
310 Region::const_iterator const tail = region.end();
311 while (cur != tail) {
312 if (first) {
313 first = false;
314 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800315 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800317 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318 cur++;
319 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000320 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321}
322
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000323std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
324 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500325 constexpr size_t maxEntries = 50; // max events to print
326 constexpr size_t skipBegin = maxEntries / 2;
327 const size_t skipEnd = queue.size() - maxEntries / 2;
328 // skip from maxEntries / 2 ... size() - maxEntries/2
329 // only print from 0 .. skipBegin and then from skipEnd .. size()
330
331 std::string dump;
332 for (size_t i = 0; i < queue.size(); i++) {
333 const DispatchEntry& entry = *queue[i];
334 if (i >= skipBegin && i < skipEnd) {
335 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
336 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
337 continue;
338 }
339 dump.append(INDENT4);
340 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000341 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
342 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500343 ns2ms(currentTime - entry.eventEntry->eventTime));
344 if (entry.deliveryTime != 0) {
345 // This entry was delivered, so add information on how long we've been waiting
346 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
347 }
348 dump.append("\n");
349 }
350 return dump;
351}
352
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700353/**
354 * Find the entry in std::unordered_map by key, and return it.
355 * If the entry is not found, return a default constructed entry.
356 *
357 * Useful when the entries are vectors, since an empty vector will be returned
358 * if the entry is not found.
359 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
360 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700361template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700363 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700364 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800365}
366
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700368 if (first == second) {
369 return true;
370 }
371
372 if (first == nullptr || second == nullptr) {
373 return false;
374 }
375
376 return first->getToken() == second->getToken();
377}
378
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000379bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000380 if (first == nullptr || second == nullptr) {
381 return false;
382 }
383 return first->applicationInfo.token != nullptr &&
384 first->applicationInfo.token == second->applicationInfo.token;
385}
386
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800387template <typename T>
388size_t firstMarkedBit(T set) {
389 // TODO: replace with std::countr_zero from <bit> when that's available
390 LOG_ALWAYS_FATAL_IF(set.none());
391 size_t i = 0;
392 while (!set.test(i)) {
393 i++;
394 }
395 return i;
396}
397
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000398std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
399 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000400 std::shared_ptr<const EventEntry> eventEntry,
401 ftl::Flags<InputTarget::Flags> inputTargetFlags,
402 int64_t vsyncId) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000403 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000404 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
405 const std::optional<int32_t> windowId =
406 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
407 // Assume the only targets that are not associated with a window are global monitors, and use
408 // the system UID for global monitors for tracing purposes.
409 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000410
411 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700412 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700413 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700414 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000415 inputTarget.globalScaleFactor, uid, vsyncId,
416 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000417 }
418
419 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
421
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000422 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000423
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000424 const ui::Transform* transform = &kIdentityTransform;
425 const ui::Transform* displayTransform = &kIdentityTransform;
426 if (zeroCoords) {
427 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
428 } else {
429 // Use the first pointer information to normalize all other pointers. This could be any
430 // pointer as long as all other pointers are normalized to the same value and the final
431 // DispatchEntry uses the transform for the normalized pointer.
432 transform =
433 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
434 const ui::Transform inverseTransform = transform->inverse();
435 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000436
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000437 // Iterate through all pointers in the event to normalize against the first.
438 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
439 PointerCoords& newCoords = pointerCoords[i];
440 const auto pointerId = motionEntry.pointerProperties[i].id;
441 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000442
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000443 newCoords.copyFrom(motionEntry.pointerCoords[i]);
444 // First, apply the current pointer's transform to update the coordinates into
445 // window space.
446 newCoords.transform(currTransform);
447 // Next, apply the inverse transform of the normalized coordinates so the
448 // current coordinates are transformed into the normalized coordinate space.
449 newCoords.transform(inverseTransform);
450 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000451 }
452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700453 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000454 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000455 motionEntry.eventTime, motionEntry.deviceId,
456 motionEntry.source, motionEntry.displayId,
457 motionEntry.policyFlags, motionEntry.action,
458 motionEntry.actionButton, motionEntry.flags,
459 motionEntry.metaState, motionEntry.buttonState,
460 motionEntry.classification, motionEntry.edgeFlags,
461 motionEntry.xPrecision, motionEntry.yPrecision,
462 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
463 motionEntry.downTime, motionEntry.pointerProperties,
464 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000465
466 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700467 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000468 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000469 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000470 return dispatchEntry;
471}
472
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500473template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000474bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500475 if (lhs == nullptr && rhs == nullptr) {
476 return true;
477 }
478 if (lhs == nullptr || rhs == nullptr) {
479 return false;
480 }
481 return *lhs == *rhs;
482}
483
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000484KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000485 KeyEvent event;
486 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
487 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
488 entry.repeatCount, entry.downTime, entry.eventTime);
489 return event;
490}
491
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000492bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 // Do not keep track of gesture monitors. They receive every event and would disproportionately
494 // affect the statistics.
495 if (connection.monitor) {
496 return false;
497 }
498 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
499 if (!connection.responsive) {
500 return false;
501 }
502 return true;
503}
504
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000505bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000506 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
507 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000508 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
509 return false;
510 }
511 // Only track latency for events that originated from hardware
512 if (eventEntry.isSynthesized()) {
513 return false;
514 }
515 const EventEntry::Type& inputEventEntryType = eventEntry.type;
516 if (inputEventEntryType == EventEntry::Type::KEY) {
517 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
518 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
519 return false;
520 }
521 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
522 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
523 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
524 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
525 return false;
526 }
527 } else {
528 // Not a key or a motion
529 return false;
530 }
531 if (!shouldReportMetricsForConnection(connection)) {
532 return false;
533 }
534 return true;
535}
536
Prabir Pradhancef936d2021-07-21 16:17:52 +0000537/**
538 * Connection is responsive if it has no events in the waitQueue that are older than the
539 * current time.
540 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000541bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000542 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000543 for (const auto& dispatchEntry : connection.waitQueue) {
544 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000545 return false;
546 }
547 }
548 return true;
549}
550
Antonio Kantekf16f2832021-09-28 04:39:20 +0000551// Returns true if the event type passed as argument represents a user activity.
552bool isUserActivityEvent(const EventEntry& eventEntry) {
553 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000554 case EventEntry::Type::CONFIGURATION_CHANGED:
555 case EventEntry::Type::DEVICE_RESET:
556 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000557 case EventEntry::Type::FOCUS:
558 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000559 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000560 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000561 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000562 case EventEntry::Type::KEY:
563 case EventEntry::Type::MOTION:
564 return true;
565 }
566}
567
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800568// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000569bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000570 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800571 const auto inputConfig = windowInfo.inputConfig;
572 if (windowInfo.displayId != displayId ||
573 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800574 return false;
575 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700576 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800577 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800578 return false;
579 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000580
581 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
582 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
583 // the window. Points on the right and bottom edges should not be inside the window, so we need
584 // to be careful about performing a hit test when the display is rotated, since the "right" and
585 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
586 // logical display in which WM determined the bounds. Perform the hit test in the logical
587 // display space to ensure these edges are considered correctly in all orientations.
588 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
589 const auto p = displayTransform.transform(x, y);
590 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800591 return false;
592 }
593 return true;
594}
595
Prabir Pradhand65552b2021-10-07 11:23:50 -0700596bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
597 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000598 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700599}
600
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800601// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000602// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
603// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
604// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800605// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000606bool canReceiveForegroundTouches(const WindowInfo& info) {
607 // A non-touchable window can still receive touch events (e.g. in the case of
608 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
609 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
610}
611
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000612bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700613 if (windowHandle == nullptr) {
614 return false;
615 }
616 const WindowInfo* windowInfo = windowHandle->getInfo();
617 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
618 return true;
619 }
620 return false;
621}
622
Prabir Pradhan5735a322022-04-11 17:23:34 +0000623// Checks targeted injection using the window's owner's uid.
624// Returns an empty string if an entry can be sent to the given window, or an error message if the
625// entry is a targeted injection whose uid target doesn't match the window owner.
626std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
627 const EventEntry& entry) {
628 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
629 // The event was not injected, or the injected event does not target a window.
630 return {};
631 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000632 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000633 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000634 return StringPrintf("No valid window target for injection into uid %s.",
635 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000636 }
637 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000638 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
639 "owned by uid %s.",
640 uid.toString().c_str(), window->getName().c_str(),
641 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000642 }
643 return {};
644}
645
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000646std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700647 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
648 // Always dispatch mouse events to cursor position.
649 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000650 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700651 }
652
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700653 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000654 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
655 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700656}
657
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700658std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
659 if (eventEntry.type == EventEntry::Type::KEY) {
660 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
661 return keyEntry.downTime;
662 } else if (eventEntry.type == EventEntry::Type::MOTION) {
663 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
664 return motionEntry.downTime;
665 }
666 return std::nullopt;
667}
668
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000669/**
670 * Compare the old touch state to the new touch state, and generate the corresponding touched
671 * windows (== input targets).
672 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
673 * If the pointer just entered the new window, produce HOVER_ENTER.
674 * For pointers remaining in the window, produce HOVER_MOVE.
675 */
676std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
677 const TouchState& newTouchState,
678 const MotionEntry& entry) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000679 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700680
681 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
682 // ACTION_SCROLL events should not affect the hovering pointer dispatch
683 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 }
Linnan Li41859c42024-03-05 16:20:34 +0000685 std::vector<TouchedWindow> out;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000686
687 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800688 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000689
690 std::set<sp<WindowInfoHandle>> oldWindows;
691 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800692 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000693 }
694
695 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800696 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000697
698 // If the pointer is no longer in the new window set, send HOVER_EXIT.
699 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
700 if (newWindows.find(oldWindow) == newWindows.end()) {
701 TouchedWindow touchedWindow;
702 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000703 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000704 out.push_back(touchedWindow);
705 }
706 }
707
708 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
709 TouchedWindow touchedWindow;
710 touchedWindow.windowHandle = newWindow;
711 if (oldWindows.find(newWindow) == oldWindows.end()) {
712 // Any windows that have this pointer now, and didn't have it before, should get
713 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000714 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000715 } else {
716 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700717 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700718 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000719 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
720 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700721 // The Accessibility injected touch exploration event stream
722 // has known inconsistencies, so log ERROR instead of
723 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700724 severity = android::base::LogSeverity::ERROR;
725 }
726 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700727 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000728 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000729 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800730 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000731 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
732 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
733 }
734 out.push_back(touchedWindow);
735 }
736 return out;
737}
738
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800739template <typename T>
740std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
741 left.insert(left.end(), right.begin(), right.end());
742 return left;
743}
744
Harry Cuttsb166c002023-05-09 13:06:05 +0000745// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
746// both.
747void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
748 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
749 if (!window.windowHandle->getInfo()->inputConfig.test(
750 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
751 // In addition to TouchState, erase this window from the input targets! We don't have a
752 // good way to do this today except by adding a nested loop.
753 // TODO(b/282025641): simplify this code once InputTargets are being identified
754 // separately from TouchedWindows.
755 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800756 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000757 });
758 return true;
759 }
760 return false;
761 });
762}
763
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700764/**
765 * In general, touch should be always split between windows. Some exceptions:
766 * 1. Don't split touch if all of the below is true:
767 * (a) we have an active pointer down *and*
768 * (b) a new pointer is going down that's from the same device *and*
769 * (c) the window that's receiving the current pointer does not support split touch.
770 * 2. Don't split mouse events
771 */
772bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
773 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
774 // We should never split mouse events
775 return false;
776 }
777 for (const TouchedWindow& touchedWindow : touchState.windows) {
778 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
779 // Spy windows should not affect whether or not touch is split.
780 continue;
781 }
782 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
783 continue;
784 }
785 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
786 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
787 // Wallpaper window should not affect whether or not touch is split
788 continue;
789 }
790
791 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
792 return false;
793 }
794 }
795 return true;
796}
797
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700798/**
799 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
800 */
801bool isStylusActiveInDisplay(
802 int32_t displayId,
803 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
804 const auto it = touchStatesByDisplay.find(displayId);
805 if (it == touchStatesByDisplay.end()) {
806 return false;
807 }
808 const TouchState& state = it->second;
809 return state.hasActiveStylus();
810}
811
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800812Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
813 struct HashFunction {
814 size_t operator()(const WindowInfo& info) const { return info.id; }
815 };
816
817 std::unordered_set<WindowInfo, HashFunction> windowSet;
818 for (const WindowInfo& info : update.windowInfos) {
819 const auto [_, inserted] = windowSet.insert(info);
820 if (!inserted) {
821 return Error() << "Duplicate entry for " << info;
822 }
823 }
824 return {};
825}
826
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800827int32_t getUserActivityEventType(const EventEntry& eventEntry) {
828 switch (eventEntry.type) {
829 case EventEntry::Type::KEY: {
830 return USER_ACTIVITY_EVENT_BUTTON;
831 }
832 case EventEntry::Type::MOTION: {
833 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
834 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
835 return USER_ACTIVITY_EVENT_TOUCH;
836 }
837 return USER_ACTIVITY_EVENT_OTHER;
838 }
839 default: {
840 LOG_ALWAYS_FATAL("%s events are not user activity",
841 ftl::enum_string(eventEntry.type).c_str());
842 }
843 }
844}
845
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000846std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
847 CancelationOptions::Mode mode) {
848 switch (mode) {
849 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
850 return {true, true};
851 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
852 return {true, false};
853 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
854 return {false, true};
855 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
856 return {false, true};
857 }
858}
859
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000860} // namespace
861
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862// --- InputDispatcher ---
863
Prabir Pradhana41d2442023-04-20 21:30:40 +0000864InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000865 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000866
867InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
868 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700869 : mPolicy(policy),
870 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800872 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800873 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700874 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800875 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700876 mDispatchEnabled(false),
877 mDispatchFrozen(false),
878 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100879 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000880 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800881 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000882 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000883 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700884 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800885 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700887 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700888#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700889 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700890#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700891 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000892
893 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000894 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000895 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800896
897 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898}
899
900InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000901 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902
Prabir Pradhancef936d2021-07-21 16:17:52 +0000903 resetKeyRepeatLocked();
904 releasePendingEventLocked();
905 drainInboundQueueLocked();
906 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000908 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700909 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800910 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912}
913
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700914status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700915 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700916 return ALREADY_EXISTS;
917 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700918 mThread = std::make_unique<InputThread>(
919 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
920 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700921}
922
923status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700924 if (mThread && mThread->isCallingThread()) {
925 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700926 return INVALID_OPERATION;
927 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700928 mThread.reset();
929 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700930}
931
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700933 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800935 std::scoped_lock _l(mLock);
936 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 // Run a dispatch loop if there are no pending commands.
939 // The dispatch loop might enqueue commands to run afterwards.
940 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800941 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 }
943
944 // Run all pending commands if there are any.
945 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000946 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700947 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800949
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 // If we are still waiting for ack on some events,
951 // we might have to wake up earlier to check if an app is anr'ing.
952 const nsecs_t nextAnrCheck = processAnrsLocked();
953 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
954
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800955 // We are about to enter an infinitely long sleep, because we have no commands or
956 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700957 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800958 mDispatcherEnteredIdle.notify_all();
959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 } // release lock
961
962 // Wait for callback or timeout or wake. (make sure we round up, not down)
963 nsecs_t currentTime = now();
964 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
965 mLooper->pollOnce(timeoutMillis);
966}
967
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500969 * Raise ANR if there is no focused window.
970 * Before the ANR is raised, do a final state check:
971 * 1. The currently focused application must be the same one we are waiting for.
972 * 2. Ensure we still don't have a focused window.
973 */
974void InputDispatcher::processNoFocusedWindowAnrLocked() {
975 // Check if the application that we are waiting for is still focused.
976 std::shared_ptr<InputApplicationHandle> focusedApplication =
977 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
978 if (focusedApplication == nullptr ||
979 focusedApplication->getApplicationToken() !=
980 mAwaitedFocusedApplication->getApplicationToken()) {
981 // Unexpected because we should have reset the ANR timer when focused application changed
982 ALOGE("Waited for a focused window, but focused application has already changed to %s",
983 focusedApplication->getName().c_str());
984 return; // The focused application has changed.
985 }
986
chaviw98318de2021-05-19 16:45:23 -0500987 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500988 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
989 if (focusedWindowHandle != nullptr) {
990 return; // We now have a focused window. No need for ANR.
991 }
992 onAnrLocked(mAwaitedFocusedApplication);
993}
994
995/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 * Check if any of the connections' wait queues have events that are too old.
997 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
998 * Return the time at which we should wake up next.
999 */
1000nsecs_t InputDispatcher::processAnrsLocked() {
1001 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001002 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001003 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1004 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1005 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001006 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001007 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001008 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001009 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001010 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001011 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001012 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1013 }
1014 }
1015
1016 // Check if any connection ANRs are due
1017 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1018 if (currentTime < nextAnrCheck) { // most likely scenario
1019 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1020 }
1021
1022 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001023 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001024 if (connection == nullptr) {
1025 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1026 return nextAnrCheck;
1027 }
1028 connection->responsive = false;
1029 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001030 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001031 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001032 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033}
1034
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001035std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001036 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001037 if (connection->monitor) {
1038 return mMonitorDispatchingTimeout;
1039 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001040 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001041 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001042 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001043 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001044 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001045}
1046
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001047void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 nsecs_t currentTime = now();
1049
Jeff Browndc5992e2014-04-11 01:27:26 -07001050 // Reset the key repeat timer whenever normal dispatch is suspended while the
1051 // device is in a non-interactive state. This is to ensure that we abort a key
1052 // repeat if the device is just coming out of sleep.
1053 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 resetKeyRepeatLocked();
1055 }
1056
1057 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1058 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001059 if (DEBUG_FOCUS) {
1060 ALOGD("Dispatch frozen. Waiting some more.");
1061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 return;
1063 }
1064
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 // Ready to start a new event.
1066 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001068 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 // Synthesize a key repeat if appropriate.
1070 if (mKeyRepeatState.lastKeyEntry) {
1071 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1072 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1073 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001074 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076 }
1077
1078 // Nothing to do if there is no pending event.
1079 if (!mPendingEvent) {
1080 return;
1081 }
1082 } else {
1083 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001084 mPendingEvent = mInboundQueue.front();
1085 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 traceInboundQueueLengthLocked();
1087 }
1088
1089 // Poke user activity for this event.
1090 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001091 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094
1095 // Now we have an event to dispatch.
1096 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001097 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001101 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
1105
1106 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109
1110 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 const ConfigurationChangedEntry& typedEntry =
1113 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001119 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001120 const DeviceResetEntry& typedEntry =
1121 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001127 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001128 std::shared_ptr<const FocusEntry> typedEntry =
1129 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001130 dispatchFocusLocked(currentTime, typedEntry);
1131 done = true;
1132 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1133 break;
1134 }
1135
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001136 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001137 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001138 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1139 done = true;
1140 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1141 break;
1142 }
1143
Prabir Pradhan99987712020-11-10 18:43:05 -08001144 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1145 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001146 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001147 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1148 done = true;
1149 break;
1150 }
1151
arthurhungb89ccb02020-12-30 16:19:01 +08001152 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001153 std::shared_ptr<const DragEntry> typedEntry =
1154 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001155 dispatchDragLocked(currentTime, typedEntry);
1156 done = true;
1157 break;
1158 }
1159
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001160 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001161 std::shared_ptr<const KeyEntry> keyEntry =
1162 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001164 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1167 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 break;
1171 }
1172
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001173 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001174 std::shared_ptr<const MotionEntry> motionEntry =
1175 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001176 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001177 // The event is stale. However, only drop stale events if there isn't an ongoing
1178 // gesture. That would allow us to complete the processing of the current stroke.
1179 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1180 if (touchStateIt != mTouchStatesByDisplay.end()) {
1181 const TouchState& touchState = touchStateIt->second;
1182 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1183 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1184 dropReason = DropReason::STALE;
1185 }
1186 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001188 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001189 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1190 // Only drop events that are focus-dispatched.
1191 dropReason = DropReason::BLOCKED;
1192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
Chris Yef59a2f42020-10-16 12:55:26 -07001197
1198 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001199 std::shared_ptr<const SensorEntry> sensorEntry =
1200 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001201
Chris Yef59a2f42020-10-16 12:55:26 -07001202 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1203 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1204 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1205 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1206 dropReason = DropReason::STALE;
1207 }
1208 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1209 done = true;
1210 break;
1211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213
1214 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
Michael Wright3a981722015-06-10 15:26:13 +01001218 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001220 if (mTracer) {
1221 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
1222 mTracer->eventProcessingComplete(*traceTracker);
1223 }
1224 }
1225
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001227 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229}
1230
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001231bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001232 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001233}
1234
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235/**
1236 * Return true if the events preceding this incoming motion event should be dropped
1237 * Return false otherwise (the default behaviour)
1238 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001239bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001241 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001242
1243 // Optimize case where the current application is unresponsive and the user
1244 // decides to touch a window in a different application.
1245 // If the application takes too long to catch up then we drop all events preceding
1246 // the touch into the other window.
1247 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001248 const int32_t displayId = motionEntry.displayId;
1249 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001250 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001251
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001252 sp<WindowInfoHandle> touchedWindowHandle =
1253 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001255 touchedWindowHandle->getApplicationToken() !=
1256 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001257 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001258 ALOGI("Pruning input queue because user touched a different application while waiting "
1259 "for %s",
1260 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001261 return true;
1262 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001263
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001264 // Alternatively, maybe there's a spy window that could handle this event.
1265 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1266 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1267 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001268 const std::shared_ptr<Connection> connection =
1269 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001270 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001271 // This spy window could take more input. Drop all events preceding this
1272 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001273 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001274 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001275 mAwaitedFocusedApplication->getName().c_str());
1276 return true;
1277 }
1278 }
1279 }
1280
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281 return false;
1282}
1283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001285 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001287 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 traceInboundQueueLengthLocked();
1289
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001291 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001292 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1293 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001296 if (mTracer) {
1297 ensureEventTraced(keyEntry);
1298 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001299
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001300 // If a new up event comes in, and the pending event with same key code has been asked
1301 // to try again later because of the policy. We have to reset the intercept key wake up
1302 // time for it may have been handled in the policy and could be dropped.
1303 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1304 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001305 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001306 if (pendingKey.keyCode == keyEntry.keyCode &&
1307 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001308 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1309 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001310 pendingKey.interceptKeyWakeupTime = 0;
1311 needWake = true;
1312 }
1313 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 break;
1315 }
1316
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001317 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001318 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1319 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001320 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1321 if (mTracer) {
1322 ensureEventTraced(motionEntry);
1323 }
1324 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001326 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001328
1329 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1330 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1331 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1332 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1333 // and some other events have not yet been processed, the dispatcher will wait for
1334 // these events to be processed before dispatching the key event. This is because
1335 // the unprocessed events may cause the focus to change (for example, by launching a
1336 // new window or tapping a different window). To prevent waiting too long, we force
1337 // the key to be sent to the currently focused window when a new tap comes in.
1338 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1339 "just send the pending key event to the currently focused window.");
1340 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001341 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001342 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001343 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001346 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1347 break;
1348 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001349 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001350 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001351 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001352 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001353 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1354 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001355 // nothing to do
1356 break;
1357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 return needWake;
1361}
1362
Prabir Pradhan24047542023-11-02 17:14:59 +00001363void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001364 // Do not store sensor event in recent queue to avoid flooding the queue.
1365 if (entry->type != EventEntry::Type::SENSOR) {
1366 mRecentQueue.push_back(entry);
1367 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001368 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001369 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 }
1371}
1372
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001373sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1374 bool isStylus,
1375 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001377 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001378 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001379 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001380 continue;
1381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001383 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001384 if (!info.isSpy() &&
1385 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001386 return windowHandle;
1387 }
1388 }
1389 return nullptr;
1390}
1391
1392std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001393 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001394 if (touchedWindow == nullptr) {
1395 return {};
1396 }
1397 // Traverse windows from front to back until we encounter the touched window.
1398 std::vector<InputTarget> outsideTargets;
1399 const auto& windowHandles = getWindowHandlesLocked(displayId);
1400 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1401 if (windowHandle == touchedWindow) {
1402 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1403 // below the touched window will not get ACTION_OUTSIDE event.
1404 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001405 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001406
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001407 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001408 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001409 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1410 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001411 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1412 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001413 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001416 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417}
1418
Prabir Pradhand65552b2021-10-07 11:23:50 -07001419std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001420 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001421 // Traverse windows from front to back and gather the touched spy windows.
1422 std::vector<sp<WindowInfoHandle>> spyWindows;
1423 const auto& windowHandles = getWindowHandlesLocked(displayId);
1424 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1425 const WindowInfo& info = *windowHandle->getInfo();
1426
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001427 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001428 continue;
1429 }
1430 if (!info.isSpy()) {
1431 // The first touched non-spy window was found, so return the spy windows touched so far.
1432 return spyWindows;
1433 }
1434 spyWindows.push_back(windowHandle);
1435 }
1436 return spyWindows;
1437}
1438
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 const char* reason;
1441 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001442 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001443 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001444 ALOGD("Dropped event because policy consumed it.");
1445 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 reason = "inbound event was dropped because the policy consumed it";
1447 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001448 case DropReason::DISABLED:
1449 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 ALOGI("Dropped event because input dispatch is disabled.");
1451 }
1452 reason = "inbound event was dropped because input dispatch is disabled";
1453 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001454 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001455 LOG(INFO) << "Dropping because the current application is not responding and the user "
1456 "has started interacting with a different application: "
1457 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001458 reason = "inbound event was dropped because the current application is not responding "
1459 "and the user has started interacting with a different application";
1460 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001461 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 ALOGI("Dropped event because it is stale.");
1463 reason = "inbound event was dropped because it is stale";
1464 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001465 case DropReason::NO_POINTER_CAPTURE:
1466 ALOGI("Dropped event because there is no window with Pointer Capture.");
1467 reason = "inbound event was dropped because there is no window with Pointer Capture";
1468 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001469 case DropReason::NOT_DROPPED: {
1470 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 }
1474
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001475 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001476 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001477 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001478 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1479 options.displayId = keyEntry.displayId;
1480 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001484 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1486 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001487 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001488 options.displayId = motionEntry.displayId;
1489 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 synthesizeCancelationEventsForAllConnectionsLocked(options);
1491 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001492 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1493 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001494 options.displayId = motionEntry.displayId;
1495 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 synthesizeCancelationEventsForAllConnectionsLocked(options);
1497 }
1498 break;
1499 }
Chris Yef59a2f42020-10-16 12:55:26 -07001500 case EventEntry::Type::SENSOR: {
1501 break;
1502 }
arthurhungb89ccb02020-12-30 16:19:01 +08001503 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1504 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001505 break;
1506 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001507 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001508 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001509 case EventEntry::Type::CONFIGURATION_CHANGED:
1510 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001511 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001512 break;
1513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515}
1516
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001518 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
Prabir Pradhancef936d2021-07-21 16:17:52 +00001521bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001522 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 return false;
1524 }
1525
1526 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001527 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001528 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1530 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001531 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533}
1534
Prabir Pradhancef936d2021-07-21 16:17:52 +00001535void InputDispatcher::postCommandLocked(Command&& command) {
1536 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537}
1538
1539void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001540 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001541 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001542 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 releaseInboundEventLocked(entry);
1544 }
1545 traceInboundQueueLengthLocked();
1546}
1547
1548void InputDispatcher::releasePendingEventLocked() {
1549 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001551 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 }
1553}
1554
Prabir Pradhan24047542023-11-02 17:14:59 +00001555void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001556 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001558 if (DEBUG_DISPATCH_CYCLE) {
1559 ALOGD("Injected inbound event was dropped.");
1560 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 }
1563 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001564 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 }
1566 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567}
1568
1569void InputDispatcher::resetKeyRepeatLocked() {
1570 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001571 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573}
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001576 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
Michael Wright2e732952014-09-24 13:26:59 -07001578 uint32_t policyFlags = entry->policyFlags &
1579 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001582 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1583 currentTime, entry->deviceId, entry->source,
1584 entry->displayId, policyFlags, entry->action, entry->flags,
1585 entry->keyCode, entry->scanCode, entry->metaState,
1586 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001589 if (mTracer) {
1590 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1591 }
1592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596}
1597
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001598bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001599 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1601 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
1604 // Reset key repeating in case a keyboard device was added or removed or something.
1605 resetKeyRepeatLocked();
1606
1607 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001608 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1609 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001610 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001611 };
1612 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 return true;
1614}
1615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001616bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1617 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1619 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1620 entry.deviceId);
1621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
liushenxiang42232912021-05-21 20:24:09 +08001623 // Reset key repeating in case a keyboard device was disabled or enabled.
1624 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1625 resetKeyRepeatLocked();
1626 }
1627
Michael Wrightfb04fd52022-11-24 22:31:11 +00001628 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001629 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001631
1632 // Remove all active pointers from this device
1633 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1634 touchState.removeAllPointersForDevice(entry.deviceId);
1635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return true;
1637}
1638
Vishnu Nairad321cd2020-08-20 16:40:21 -07001639void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001640 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001641 if (mPendingEvent != nullptr) {
1642 // Move the pending event to the front of the queue. This will give the chance
1643 // for the pending event to get dispatched to the newly focused window
1644 mInboundQueue.push_front(mPendingEvent);
1645 mPendingEvent = nullptr;
1646 }
1647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648 std::unique_ptr<FocusEntry> focusEntry =
1649 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1650 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001651
1652 // This event should go to the front of the queue, but behind all other focus events
1653 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001654 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1655 [](const std::shared_ptr<const EventEntry>& event) {
1656 return event->type == EventEntry::Type::FOCUS;
1657 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001658
1659 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001660 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001661}
1662
Prabir Pradhan24047542023-11-02 17:14:59 +00001663void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1664 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001665 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1666 if (connection == nullptr) {
1667 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001668 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001669 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001670 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001671 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001672 std::string reason = std::string("reason=").append(entry->reason);
1673 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001674 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001675}
1676
Prabir Pradhan99987712020-11-10 18:43:05 -08001677void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001678 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001679 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001680 dropReason = DropReason::NOT_DROPPED;
1681
Prabir Pradhan99987712020-11-10 18:43:05 -08001682 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001683 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001684
1685 if (entry->pointerCaptureRequest.enable) {
1686 // Enable Pointer Capture.
1687 if (haveWindowWithPointerCapture &&
1688 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001689 // This can happen if pointer capture is disabled and re-enabled before we notify the
1690 // app of the state change, so there is no need to notify the app.
1691 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1692 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001693 }
1694 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001695 // This can happen if a window requests capture and immediately releases capture.
1696 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001697 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001698 return;
1699 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001700 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1701 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1702 return;
1703 }
1704
Vishnu Nairc519ff72021-01-21 08:23:08 -08001705 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001706 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1707 mWindowTokenWithPointerCapture = token;
1708 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001709 // Disable Pointer Capture.
1710 // We do not check if the sequence number matches for requests to disable Pointer Capture
1711 // for two reasons:
1712 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1713 // to disable capture with the same sequence number: one generated by
1714 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1715 // Capture being disabled in InputReader.
1716 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1717 // actual Pointer Capture state that affects events being generated by input devices is
1718 // in InputReader.
1719 if (!haveWindowWithPointerCapture) {
1720 // Pointer capture was already forcefully disabled because of focus change.
1721 dropReason = DropReason::NOT_DROPPED;
1722 return;
1723 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001724 token = mWindowTokenWithPointerCapture;
1725 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001726 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001727 setPointerCaptureLocked(false);
1728 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001729 }
1730
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001731 auto connection = getConnectionLocked(token);
1732 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001733 // Window has gone away, clean up Pointer Capture state.
1734 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001735 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001736 setPointerCaptureLocked(false);
1737 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001738 return;
1739 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001740 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001741 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001742
1743 dropReason = DropReason::NOT_DROPPED;
1744}
1745
Prabir Pradhan24047542023-11-02 17:14:59 +00001746void InputDispatcher::dispatchTouchModeChangeLocked(
1747 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001748 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001749 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001750 if (windowHandles.empty()) {
1751 return;
1752 }
1753 const std::vector<InputTarget> inputTargets =
1754 getInputTargetsFromWindowHandlesLocked(windowHandles);
1755 if (inputTargets.empty()) {
1756 return;
1757 }
1758 entry->dispatchInProgress = true;
1759 dispatchEventLocked(currentTime, entry, inputTargets);
1760}
1761
1762std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1763 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1764 std::vector<InputTarget> inputTargets;
1765 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001766 const sp<IBinder>& token = handle->getToken();
1767 if (token == nullptr) {
1768 continue;
1769 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001770 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1771 if (connection == nullptr) {
1772 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001773 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001774 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001775 }
1776 return inputTargets;
1777}
1778
Prabir Pradhan24047542023-11-02 17:14:59 +00001779bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001780 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 if (!entry->dispatchInProgress) {
1783 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1784 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1785 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1786 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001787 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 // We have seen two identical key downs in a row which indicates that the device
1789 // driver is automatically generating key repeats itself. We take note of the
1790 // repeat here, but we disable our own next key repeat timer since it is clear that
1791 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001792 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1793 // Make sure we don't get key down from a different device. If a different
1794 // device Id has same key pressed down, the new device Id will replace the
1795 // current one to hold the key repeat with repeat count reset.
1796 // In the future when got a KEY_UP on the device id, drop it and do not
1797 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1799 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001800 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 } else {
1802 // Not a repeat. Save key down state in case we do see a repeat later.
1803 resetKeyRepeatLocked();
1804 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1805 }
1806 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001807 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1808 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001809 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001810 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001811 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1812 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001813 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 resetKeyRepeatLocked();
1815 }
1816
1817 if (entry->repeatCount == 1) {
1818 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1819 } else {
1820 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1821 }
1822
1823 entry->dispatchInProgress = true;
1824
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827
1828 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001829 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001831 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 return false; // wait until next wakeup
1833 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001834 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 entry->interceptKeyWakeupTime = 0;
1836 }
1837
1838 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001839 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001841 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001842 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001843
1844 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1845 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1846 };
1847 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001848 // Poke user activity for keys not passed to user
1849 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return false; // wait for the command to run
1851 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001852 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001854 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001855 if (*dropReason == DropReason::NOT_DROPPED) {
1856 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 }
1858 }
1859
1860 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001861 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001862 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1864 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001865 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001866 // Poke user activity for undispatched keys
1867 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return true;
1869 }
1870
1871 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001872 InputEventInjectionResult injectionResult;
1873 sp<WindowInfoHandle> focusedWindow =
1874 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1875 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 return false;
1878 }
1879
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001880 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 return true;
1883 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001884 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1885
1886 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001887 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1888 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001890 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001893 if (mTracer) {
1894 ensureEventTraced(*entry);
1895 for (const auto& target : inputTargets) {
1896 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1897 }
1898 }
1899
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 // Dispatch the key.
1901 dispatchEventLocked(currentTime, entry, inputTargets);
1902 return true;
1903}
1904
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001905void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1907 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1908 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1909 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1910 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1911 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1912 entry.metaState, entry.repeatCount, entry.downTime);
1913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914}
1915
Prabir Pradhancef936d2021-07-21 16:17:52 +00001916void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001917 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001918 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001919 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1920 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1921 "source=0x%x, sensorType=%s",
1922 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001923 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001925 auto command = [this, entry]() REQUIRES(mLock) {
1926 scoped_unlock unlock(mLock);
1927
1928 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001929 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001930 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001931 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1932 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001933 };
1934 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001935}
1936
1937bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1939 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001940 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001941 }
Chris Yef59a2f42020-10-16 12:55:26 -07001942 { // acquire lock
1943 std::scoped_lock _l(mLock);
1944
1945 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001946 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001947 if (entry->type == EventEntry::Type::SENSOR) {
1948 it = mInboundQueue.erase(it);
1949 releaseInboundEventLocked(entry);
1950 }
1951 }
1952 }
1953 return true;
1954}
1955
Prabir Pradhan24047542023-11-02 17:14:59 +00001956bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1957 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001958 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001961 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 entry->dispatchInProgress = true;
1963
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001964 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966
1967 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001968 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001969 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1971 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 return true;
1973 }
1974
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001975 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
1977 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001978 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 if (isPointerEvent) {
1982 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001983
1984 if (mDragState &&
1985 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1986 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1987 pilferPointersLocked(mDragState->dragWindow->getToken());
1988 }
1989
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001990 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001991 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001992 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1993 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else {
1995 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001996 sp<WindowInfoHandle> focusedWindow =
1997 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1998 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1999 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002000 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2001 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2002 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 return false;
2007 }
2008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002009 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002010 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002011 return true;
2012 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002014 CancelationOptions::Mode mode(
2015 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2016 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002017 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002018 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002019 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 return true;
2021 }
2022
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002023 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002026 if (mTracer) {
2027 ensureEventTraced(*entry);
2028 for (const auto& target : inputTargets) {
2029 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2030 }
2031 }
2032
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 dispatchEventLocked(currentTime, entry, inputTargets);
2035 return true;
2036}
2037
chaviw98318de2021-05-19 16:45:23 -05002038void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002039 bool isExiting, const int32_t rawX,
2040 const int32_t rawY) {
2041 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002042 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002043 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2044 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002045
2046 enqueueInboundEventLocked(std::move(dragEntry));
2047}
2048
Prabir Pradhan24047542023-11-02 17:14:59 +00002049void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2050 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002051 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2052 if (connection == nullptr) {
2053 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002054 }
arthurhungb89ccb02020-12-30 16:19:01 +08002055 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002056 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002057}
2058
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002059void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002060 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002061 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002062 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002063 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002064 "metaState=0x%x, buttonState=0x%x,"
2065 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002066 prefix, entry.eventTime, entry.deviceId,
2067 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2068 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2069 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2070 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002072 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002073 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002074 "x=%f, y=%f, pressure=%f, size=%f, "
2075 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2076 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002077 i, entry.pointerProperties[i].id,
2078 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002079 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2080 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2081 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2082 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2083 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2084 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2085 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2086 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2087 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090}
2091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002092void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002093 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002095 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002096 if (DEBUG_DISPATCH_CYCLE) {
2097 ALOGD("dispatchEventToCurrentInputTargets");
2098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002100 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002101
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2103
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002104 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002106 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002107 std::shared_ptr<Connection> connection = inputTarget.connection;
2108 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
2110}
2111
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002112void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2114 // If the policy decides to close the app, we will get a channel removal event via
2115 // unregisterInputChannel, and will clean up the connection that way. We are already not
2116 // sending new pointers to the connection when it blocked, but focused events will continue to
2117 // pile up.
2118 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002119 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002120 if (connection->status != Connection::Status::NORMAL) {
2121 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002123 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2124 "application not responding");
2125
2126 sp<WindowInfoHandle> windowHandle;
2127 if (!connection->monitor) {
2128 windowHandle = getWindowHandleLocked(connection->getToken());
2129 if (windowHandle == nullptr) {
2130 // The window that is receiving this ANR was removed, so there is no need to generate
2131 // cancellations, because the cancellations would have already been generated when
2132 // the window was removed.
2133 return;
2134 }
2135 }
2136 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137}
2138
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002140 if (DEBUG_FOCUS) {
2141 ALOGD("Resetting ANR timeouts.");
2142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
2144 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002145 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002146 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147}
2148
Tiger Huang721e26f2018-07-24 22:26:19 +08002149/**
2150 * Get the display id that the given event should go to. If this event specifies a valid display id,
2151 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2152 * Focused display is the display that the user most recently interacted with.
2153 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002155 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002157 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002158 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2159 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 break;
2161 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2164 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 break;
2166 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002167 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002168 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002169 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002170 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002171 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002172 case EventEntry::Type::SENSOR:
2173 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002174 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 return ADISPLAY_ID_NONE;
2176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002177 }
2178 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2179}
2180
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2182 const char* focusedWindowName) {
2183 if (mAnrTracker.empty()) {
2184 // already processed all events that we waited for
2185 mKeyIsWaitingForEventsTimeout = std::nullopt;
2186 return false;
2187 }
2188
2189 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2190 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002191 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002192 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002193 std::chrono::duration_cast<std::chrono::nanoseconds>(
2194 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002195 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002196 return true;
2197 }
2198
2199 // We still have pending events, and already started the timer
2200 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2201 return true; // Still waiting
2202 }
2203
2204 // Waited too long, and some connection still hasn't processed all motions
2205 // Just send the key to the focused window
2206 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2207 focusedWindowName);
2208 mKeyIsWaitingForEventsTimeout = std::nullopt;
2209 return false;
2210}
2211
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002212sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002213 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002214 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002215 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216
Tiger Huang721e26f2018-07-24 22:26:19 +08002217 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002218 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002219 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002220 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 // If there is no currently focused window and no focused application
2223 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2225 ALOGI("Dropping %s event because there is no focused window or focused application in "
2226 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002227 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002228 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Vishnu Nair062a8672021-09-03 16:07:44 -07002231 // Drop key events if requested by input feature
2232 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002233 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002234 }
2235
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2237 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2238 // start interacting with another application via touch (app switch). This code can be removed
2239 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2240 // an app is expected to have a focused window.
2241 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2242 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2243 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002244 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2245 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2246 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002248 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 ALOGW("Waiting because no window has focus but %s may eventually add a "
2250 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002251 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002252 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = InputEventInjectionResult::PENDING;
2254 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2256 // Already raised ANR. Drop the event
2257 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002258 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002259 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 } else {
2261 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::PENDING;
2263 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 }
2265 }
2266
2267 // we have a valid, non-null focused window
2268 resetNoFocusedWindowTimeoutLocked();
2269
Prabir Pradhan5735a322022-04-11 17:23:34 +00002270 // Verify targeted injection.
2271 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2272 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002273 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2274 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002277 if (focusedWindowHandle->getInfo()->inputConfig.test(
2278 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002280 outInjectionResult = InputEventInjectionResult::PENDING;
2281 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 }
2283
2284 // If the event is a key event, then we must wait for all previous events to
2285 // complete before delivering it because previous events may have the
2286 // side-effect of transferring focus to a different window and we want to
2287 // ensure that the following keys are sent to the new window.
2288 //
2289 // Suppose the user touches a button in a window then immediately presses "A".
2290 // If the button causes a pop-up window to appear then we want to ensure that
2291 // the "A" key is delivered to the new pop-up window. This is because users
2292 // often anticipate pending UI changes when typing on a keyboard.
2293 // To obtain this behavior, we must serialize key events with respect to all
2294 // prior input events.
2295 if (entry.type == EventEntry::Type::KEY) {
2296 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002297 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002298 outInjectionResult = InputEventInjectionResult::PENDING;
2299 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002303 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2304 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305}
2306
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002307/**
2308 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2309 * that are currently unresponsive.
2310 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002311std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2312 const std::vector<Monitor>& monitors) const {
2313 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002314 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002315 [](const Monitor& monitor) REQUIRES(mLock) {
2316 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002317 if (!connection->responsive) {
2318 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002319 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002320 return false;
2321 }
2322 return true;
2323 });
2324 return responsiveMonitors;
2325}
2326
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002327std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002328 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002329 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002330 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002332 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // For security reasons, we defer updating the touch state until we are sure that
2334 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335 const int32_t displayId = entry.displayId;
2336 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002337 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
2339 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002340 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002342 // Copy current touch state into tempTouchState.
2343 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2344 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002345 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002346 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002347 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2348 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002349 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002350 }
2351
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002352 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353
2354 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2355 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2356 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002357 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2358 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002359 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002360 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2361 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002362 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2363 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2364 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002365 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002366
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002367 if (newGesture) {
2368 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002369 }
2370
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002371 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2372 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2373 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002376 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002377 if (wasDown) {
2378 // Started hovering, but the device is already down: reject the hover event
2379 LOG(ERROR) << "Got hover event " << entry.getDescription()
2380 << " but the device is already down " << oldState->dump();
2381 outInjectionResult = InputEventInjectionResult::FAILED;
2382 return {};
2383 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002384 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2385 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002386 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002387 }
2388
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2390 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002391 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002392 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002393 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002394 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2395 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002396 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002397 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002398 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002399
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002400 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002401 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002404 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002405 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002408 }
2409
Prabir Pradhan5735a322022-04-11 17:23:34 +00002410 // Verify targeted injection.
2411 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2412 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002413 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002414 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002415 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002416 }
2417
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002419 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2421 // New window supports splitting, but we should never split mouse events.
2422 isSplit = !isFromMouse;
2423 } else if (isSplit) {
2424 // New window does not support splitting but we have already split events.
2425 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002426 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2427 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002428 newTouchedWindowHandle = nullptr;
2429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430 } else {
2431 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002432 // be delivered to a new window which supports split touch. Pointers from a mouse device
2433 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002434 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002435 }
2436
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002437 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002438 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002439 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002440 // Process the foreground window first so that it is the first to receive the event.
2441 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002442 }
2443
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002444 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002445 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2446 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002447 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002448 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002449 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002450 }
2451
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002452 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002453 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 continue;
2455 }
2456
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002457 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002458 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002459 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002460 }
2461
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002462 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002463 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002464
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002465 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2466 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002467 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002468 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002469
2470 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002471 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002472 }
2473 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002474 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002475 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002476 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002477 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002478
2479 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002480
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002481 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002482 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2483 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002484 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002485 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002486 isDownOrPointerDown
2487 ? std::make_optional(entry.eventTime)
2488 : std::nullopt);
2489 // If this is the pointer going down and the touched window has a wallpaper
2490 // then also add the touched wallpaper windows so they are locked in for the
2491 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2492 // SCROLL because the wallpaper engine only supports touch events. We would need to
2493 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2494 // handle these events.
2495 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002496 windowHandle->getInfo()->inputConfig.test(
2497 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2498 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2499 if (wallpaper != nullptr) {
2500 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2501 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002502 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002503 if (isSplit) {
2504 wallpaperFlags |= InputTarget::Flags::SPLIT;
2505 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002506 tempTouchState.addOrUpdateWindow(wallpaper,
2507 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002508 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002509 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002510 }
2511 }
2512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002514
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002515 // If a window is already pilfering some pointers, give it this new pointer as well and
2516 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2517 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002518 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002519 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002520 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002521 // This window is already pilfering some pointers, and this new pointer is also
2522 // going to it. Therefore, take over this pointer and don't give it to anyone
2523 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002524 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002525 }
2526 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002527
2528 // Restrict all pilfered pointers to the pilfering windows.
2529 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 } else {
2531 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2532
2533 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002534 if (!tempTouchState.isDown(entry.deviceId) &&
2535 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002536 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2537 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2538 << " is not down or we previously dropped the pointer down event in "
2539 << "display " << displayId << ": " << entry.getDescription();
2540 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002541 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002542 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002545 // If the pointer is not currently hovering, then ignore the event.
2546 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2547 const int32_t pointerId = entry.pointerProperties[0].id;
2548 if (oldState == nullptr ||
2549 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2550 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2551 "display "
2552 << displayId << ": " << entry.getDescription();
2553 outInjectionResult = InputEventInjectionResult::FAILED;
2554 return {};
2555 }
2556 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2557 }
2558
arthurhung6d4bed92021-03-17 11:59:33 +08002559 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002562 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002563 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002564 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002565 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002566 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002567 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002568 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002569 sp<WindowInfoHandle> newTouchedWindowHandle =
2570 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002571
Prabir Pradhan5735a322022-04-11 17:23:34 +00002572 // Verify targeted injection.
2573 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2574 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002575 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002576 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002577 }
2578
Linnan Libf069a32024-02-29 17:22:59 +00002579 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002580 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002581 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002582 newTouchedWindowHandle = nullptr;
2583 }
2584
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002585 if (newTouchedWindowHandle != nullptr &&
2586 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002587 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002588 oldTouchedWindowHandle->getName().c_str(),
2589 newTouchedWindowHandle->getName().c_str(), displayId);
2590
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002592 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002593 const PointerProperties& pointer = entry.pointerProperties[0];
2594 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002595
2596 const TouchedWindow& touchedWindow =
2597 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002598 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002599 InputTarget::DispatchMode::SLIPPERY_EXIT,
2600 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002601 touchedWindow.getDownTimeInTarget(entry.deviceId),
2602 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603
2604 // Make a slippery entrance into the new window.
2605 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002606 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
2608
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002609 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002610 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002611 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002614 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 }
2616 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002617 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002618 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002619 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002622 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2623 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002624 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002625 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002626
2627 // Check if the wallpaper window should deliver the corresponding event.
2628 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002629 tempTouchState, entry.deviceId, pointer, targets);
2630 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002631 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 }
2633 }
Arthur Hung96483742022-11-15 03:30:48 +00002634
2635 // Update the pointerIds for non-splittable when it received pointer down.
2636 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2637 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002638 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002639 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2640 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002641 // Ignore drag window for it should just track one pointer.
2642 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2643 continue;
2644 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002645 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002646 }
2647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002650 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002651 {
2652 std::vector<TouchedWindow> hoveringWindows =
2653 getHoveringWindowsLocked(oldState, tempTouchState, entry);
Linnan Li41859c42024-03-05 16:20:34 +00002654 // Hardcode to single hovering pointer for now.
2655 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2656 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002657 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002658 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2659 touchedWindow.targetFlags, pointerIds,
2660 touchedWindow.getDownTimeInTarget(entry.deviceId),
2661 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664
Prabir Pradhan5735a322022-04-11 17:23:34 +00002665 // Ensure that all touched windows are valid for injection.
2666 if (entry.injectionState != nullptr) {
2667 std::string errs;
2668 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002669 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2670 if (err) errs += "\n - " + *err;
2671 }
2672 if (!errs.empty()) {
2673 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002674 "%s:%s",
2675 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002676 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002677 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002678 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002679 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002680
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002681 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2682 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002684 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002685 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002686 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002687 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002688 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002689 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002690 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002691 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002692 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2693 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
2696 }
2697 }
2698 }
2699
Harry Cuttsb166c002023-05-09 13:06:05 +00002700 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2701 // only want the system UI to handle these gestures.
2702 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2703 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2704 if (isTouchpadNavGesture) {
2705 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2706 }
2707
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002708 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002709 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002710 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002711 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002712 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002713 continue;
2714 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002715 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002716 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002717 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002718 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002719
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002720 // During targeted injection, only allow owned targets to receive events
2721 std::erase_if(targets, [&](const InputTarget& target) {
2722 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2723 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2724 if (err) {
2725 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2726 << ": " << (*err);
2727 return true;
2728 }
2729 return false;
2730 });
2731
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002732 if (targets.empty()) {
2733 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2734 outInjectionResult = InputEventInjectionResult::FAILED;
2735 return {};
2736 }
2737
2738 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2739 // window that is actually receiving the entire gesture.
2740 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002741 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002742 })) {
2743 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2744 << entry.getDescription();
2745 outInjectionResult = InputEventInjectionResult::FAILED;
2746 return {};
2747 }
2748
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002749 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750
Prabir Pradhan502a7252023-12-01 16:11:24 +00002751 // Now that we have generated all of the input targets for this event, reset the dispatch
2752 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002753 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002754 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002755 }
2756
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002757 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002758 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002759 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002760 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002761 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002762 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002763 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002764 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2765 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002766 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2767 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2768 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 }
2770
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002771 // Save changes unless the action was scroll in which case the temporary touch
2772 // state was only valid for this one action.
2773 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002774 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002775 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002776 mTouchStatesByDisplay[displayId] = tempTouchState;
2777 } else {
2778 mTouchStatesByDisplay.erase(displayId);
2779 }
2780 }
2781
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002782 if (tempTouchState.windows.empty()) {
2783 mTouchStatesByDisplay.erase(displayId);
2784 }
2785
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002786 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787}
2788
arthurhung6d4bed92021-03-17 11:59:33 +08002789void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002790 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2791 // have an explicit reason to support it.
2792 constexpr bool isStylus = false;
2793
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002794 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002795 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002796 if (dropWindow) {
2797 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002798 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002799 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002800 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002801 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002802 }
2803 mDragState.reset();
2804}
2805
2806void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002807 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002808 return;
2809 }
2810
arthurhung6d4bed92021-03-17 11:59:33 +08002811 if (!mDragState->isStartDrag) {
2812 mDragState->isStartDrag = true;
2813 mDragState->isStylusButtonDownAtStart =
2814 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2815 }
2816
Arthur Hung54745652022-04-20 07:17:41 +00002817 // Find the pointer index by id.
2818 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002819 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002820 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2821 if (pointerProperties.id == mDragState->pointerId) {
2822 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002823 }
Arthur Hung54745652022-04-20 07:17:41 +00002824 }
arthurhung6d4bed92021-03-17 11:59:33 +08002825
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002826 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002827 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002828 }
2829
2830 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2831 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2832 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2833
2834 switch (maskedAction) {
2835 case AMOTION_EVENT_ACTION_MOVE: {
2836 // Handle the special case : stylus button no longer pressed.
2837 bool isStylusButtonDown =
2838 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2839 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2840 finishDragAndDrop(entry.displayId, x, y);
2841 return;
2842 }
2843
2844 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2845 // until we have an explicit reason to support it.
2846 constexpr bool isStylus = false;
2847
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002848 sp<WindowInfoHandle> hoverWindowHandle =
2849 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2850 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002851 // enqueue drag exit if needed.
2852 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2853 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2854 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002855 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002856 y);
2857 }
2858 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2859 }
2860 // enqueue drag location if needed.
2861 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002862 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002863 }
2864 break;
2865 }
2866
2867 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002868 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002869 break;
2870 }
2871 // The drag pointer is up.
2872 [[fallthrough]];
2873 case AMOTION_EVENT_ACTION_UP:
2874 finishDragAndDrop(entry.displayId, x, y);
2875 break;
2876 case AMOTION_EVENT_ACTION_CANCEL: {
2877 ALOGD("Receiving cancel when drag and drop.");
2878 sendDropWindowCommandLocked(nullptr, 0, 0);
2879 mDragState.reset();
2880 break;
2881 }
arthurhungb89ccb02020-12-30 16:19:01 +08002882 }
2883}
2884
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002885std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2886 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002887 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002888 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002889 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2890 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002891 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2892 return {};
2893 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002894 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002895 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002896 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002897 inputTarget.flags = targetFlags;
2898 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2899 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2900 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2901 if (displayInfoIt != mDisplayInfos.end()) {
2902 inputTarget.displayTransform = displayInfoIt->second.transform;
2903 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002904 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002905 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2906 }
2907 return inputTarget;
2908}
2909
chaviw98318de2021-05-19 16:45:23 -05002910void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002911 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002912 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002913 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002914 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002915 std::vector<InputTarget>::iterator it =
2916 std::find_if(inputTargets.begin(), inputTargets.end(),
2917 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002918 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002919 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002920
chaviw98318de2021-05-19 16:45:23 -05002921 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002922
2923 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002924 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002925 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2926 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002927 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002928 return;
2929 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002930 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002931 it = inputTargets.end() - 1;
2932 }
2933
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002934 if (it->flags != targetFlags) {
2935 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2936 }
2937 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2938 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2939 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2940 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002941}
2942
2943void InputDispatcher::addPointerWindowTargetLocked(
2944 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002945 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2946 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2947 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002948 if (pointerIds.none()) {
2949 for (const auto& target : inputTargets) {
2950 LOG(INFO) << "Target: " << target;
2951 }
2952 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2953 return;
2954 }
2955 std::vector<InputTarget>::iterator it =
2956 std::find_if(inputTargets.begin(), inputTargets.end(),
2957 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002958 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002959 });
2960
2961 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2962 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2963 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2964 // input targets for hovering pointers and for touching pointers.
2965 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2966 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002967 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002968 // Force the code below to create a new input target
2969 it = inputTargets.end();
2970 }
2971
2972 const WindowInfo* windowInfo = windowHandle->getInfo();
2973
2974 if (it == inputTargets.end()) {
2975 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002976 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2977 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002978 if (!target) {
2979 return;
2980 }
2981 inputTargets.push_back(*target);
2982 it = inputTargets.end() - 1;
2983 }
2984
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002985 if (it->dispatchMode != dispatchMode) {
2986 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2987 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2988 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002989 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002990 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2991 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002992 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002993 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002994 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002995 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2996 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002997
chaviw1ff3d1e2020-07-01 15:53:47 -07002998 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999}
3000
Michael Wright3dd60e22019-03-27 22:06:44 +00003001void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07003002 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003003 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3004 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003005
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003006 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003007 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003008 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3009 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003010 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3011 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003012 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003013 target.setDefaultPointerTransform(target.displayTransform);
3014 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 }
3016}
3017
Robert Carrc9bf1d32020-04-13 17:21:08 -07003018/**
3019 * Indicate whether one window handle should be considered as obscuring
3020 * another window handle. We only check a few preconditions. Actually
3021 * checking the bounds is left to the caller.
3022 */
chaviw98318de2021-05-19 16:45:23 -05003023static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3024 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003025 // Compare by token so cloned layers aren't counted
3026 if (haveSameToken(windowHandle, otherHandle)) {
3027 return false;
3028 }
3029 auto info = windowHandle->getInfo();
3030 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003031 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003032 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003033 } else if (otherInfo->alpha == 0 &&
3034 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003035 // Those act as if they were invisible, so we don't need to flag them.
3036 // We do want to potentially flag touchable windows even if they have 0
3037 // opacity, since they can consume touches and alter the effects of the
3038 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003039 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003040 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3041 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003042 } else if (info->ownerUid == otherInfo->ownerUid) {
3043 // If ownerUid is the same we don't generate occlusion events as there
3044 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003045 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003046 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003047 return false;
3048 } else if (otherInfo->displayId != info->displayId) {
3049 return false;
3050 }
3051 return true;
3052}
3053
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003054/**
3055 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3056 * untrusted, one should check:
3057 *
3058 * 1. If result.hasBlockingOcclusion is true.
3059 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3060 * BLOCK_UNTRUSTED.
3061 *
3062 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3063 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3064 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3065 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3066 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3067 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3068 *
3069 * If neither of those is true, then it means the touch can be allowed.
3070 */
3071InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003072 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3073 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003074 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003075 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003076 TouchOcclusionInfo info;
3077 info.hasBlockingOcclusion = false;
3078 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003079 info.obscuringUid = gui::Uid::INVALID;
3080 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003081 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082 if (windowHandle == otherHandle) {
3083 break; // All future windows are below us. Exit early.
3084 }
chaviw98318de2021-05-19 16:45:23 -05003085 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003086 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3087 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003088 if (DEBUG_TOUCH_OCCLUSION) {
3089 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003090 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003091 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003092 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3093 // we perform the checks below to see if the touch can be propagated or not based on the
3094 // window's touch occlusion mode
3095 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3096 info.hasBlockingOcclusion = true;
3097 info.obscuringUid = otherInfo->ownerUid;
3098 info.obscuringPackage = otherInfo->packageName;
3099 break;
3100 }
3101 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003102 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003103 float opacity =
3104 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3105 // Given windows A and B:
3106 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3107 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3108 opacityByUid[uid] = opacity;
3109 if (opacity > info.obscuringOpacity) {
3110 info.obscuringOpacity = opacity;
3111 info.obscuringUid = uid;
3112 info.obscuringPackage = otherInfo->packageName;
3113 }
3114 }
3115 }
3116 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003117 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003118 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003119 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003120 return info;
3121}
3122
chaviw98318de2021-05-19 16:45:23 -05003123std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003124 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003125 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003126 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3127 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3128 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003129 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003130 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003131 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3132 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003133 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3134 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3135 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003136 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003137}
3138
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003139bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3140 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003141 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3142 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003143 return false;
3144 }
3145 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003146 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003147 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003148 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003149 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3150 return false;
3151 }
3152 return true;
3153}
3154
chaviw98318de2021-05-19 16:45:23 -05003155bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003158 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3159 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003160 if (windowHandle == otherHandle) {
3161 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
chaviw98318de2021-05-19 16:45:23 -05003163 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003164 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003165 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 return true;
3167 }
3168 }
3169 return false;
3170}
3171
chaviw98318de2021-05-19 16:45:23 -05003172bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003173 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003174 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3175 const WindowInfo* windowInfo = windowHandle->getInfo();
3176 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003177 if (windowHandle == otherHandle) {
3178 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003179 }
chaviw98318de2021-05-19 16:45:23 -05003180 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003181 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003182 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003183 return true;
3184 }
3185 }
3186 return false;
3187}
3188
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003189std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003190 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003191 if (applicationHandle != nullptr) {
3192 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003193 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 } else {
3195 return applicationHandle->getName();
3196 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003197 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003198 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003200 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202}
3203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003205 if (!isUserActivityEvent(eventEntry)) {
3206 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003207 return;
3208 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003209
3210 const int32_t eventType = getUserActivityEventType(eventEntry);
3211 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3212 // Note that we're directly getting the time diff between the current event and the previous
3213 // event. This is assuming that the first user event always happens at a timestamp that is
3214 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3215 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3216 // value than the potential first user activity event time, so this is ok.
3217 std::chrono::nanoseconds timeSinceLastEvent =
3218 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3219 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3220 return;
3221 }
3222 }
3223
Tiger Huang721e26f2018-07-24 22:26:19 +08003224 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003225 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003226 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003227 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003228 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003229 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003230 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 }
3233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003234 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003235 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003236 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3237 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 return;
3239 }
Josep del Riob3981622023-04-18 15:49:45 +00003240 if (windowDisablingUserActivityInfo != nullptr) {
3241 if (DEBUG_DISPATCH_CYCLE) {
3242 ALOGD("Not poking user activity: disabled by window '%s'.",
3243 windowDisablingUserActivityInfo->name.c_str());
3244 }
3245 return;
3246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003249 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003250 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3251 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 return;
3253 }
Josep del Riob3981622023-04-18 15:49:45 +00003254 // If the key code is unknown, we don't consider it user activity
3255 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3256 return;
3257 }
3258 // Don't inhibit events that were intercepted or are not passed to
3259 // the apps, like system shortcuts
3260 if (windowDisablingUserActivityInfo != nullptr &&
3261 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3262 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3263 if (DEBUG_DISPATCH_CYCLE) {
3264 ALOGD("Not poking user activity: disabled by window '%s'.",
3265 windowDisablingUserActivityInfo->name.c_str());
3266 }
3267 return;
3268 }
3269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003272 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003273 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003274 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003275 break;
3276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003279 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003280 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3281 REQUIRES(mLock) {
3282 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003283 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003284 };
3285 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003289 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003290 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003291 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003292 ATRACE_NAME_IF(ATRACE_ENABLED(),
3293 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3294 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003295 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003297 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003299 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003300 inputTarget.getPointerInfoString().c_str());
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302
3303 // Skip this event if the connection status is not normal.
3304 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003305 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003306 if (DEBUG_DISPATCH_CYCLE) {
3307 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003308 connection->getInputChannelName().c_str(),
3309 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 return;
3312 }
3313
3314 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003316 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003318 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003320 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003321 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003322 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3323 logDispatchStateLocked();
3324 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3325 "target on connection "
3326 << connection->getInputChannelName() << " for "
3327 << originalMotionEntry.getDescription();
3328 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003330 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003331 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 if (!splitMotionEntry) {
3333 return; // split event was dropped
3334 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003335 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3336 std::string reason = std::string("reason=pointer cancel on split window");
3337 android_log_event_list(LOGTAG_INPUT_CANCEL)
3338 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3339 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003340 if (DEBUG_FOCUS) {
3341 ALOGD("channel '%s' ~ Split motion event.",
3342 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003343 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003344 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003345 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3346 std::move(splitMotionEntry),
3347 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 return;
3349 }
3350 }
3351
3352 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003353 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3354 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355}
3356
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003357void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3358 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3359 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003360 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003361 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3362 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003363 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003364
hongzuo liu95785e22022-09-06 02:51:35 +00003365 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003367 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
3369 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003370 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 startDispatchCycleLocked(currentTime, connection);
3372 }
3373}
3374
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003375void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003376 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003377 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003378 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3379 eventEntry->type == EventEntry::Type::MOTION;
3380 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3381 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3382 << inputTarget << " connection: " << connection->getInputChannelName()
3383 << " entry: " << eventEntry->getDescription();
3384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 // This is a new event.
3386 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003387 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003388 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3389 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003391 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3392 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003393 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003395 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003396 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003397 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3398 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003399 LOG(WARNING) << "channel " << connection->getInputChannelName()
3400 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 return; // skip the inconsistent event
3402 }
3403 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003406 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003407 std::shared_ptr<const MotionEntry> resolvedMotion =
3408 std::static_pointer_cast<const MotionEntry>(eventEntry);
3409 {
3410 // Determine the resolved motion entry.
3411 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3412 int32_t resolvedAction = motionEntry.action;
3413 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003415 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003416 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003417 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003418 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003419 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003420 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003421 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003422 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003423 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003424 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3425 }
3426 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3427 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3428 motionEntry.displayId)) {
3429 if (DEBUG_DISPATCH_CYCLE) {
3430 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3431 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3432 "enter event";
3433 }
3434 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3435 }
3436
3437 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3438 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3439 }
3440 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3441 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3442 }
3443 if (dispatchEntry->targetFlags.test(
3444 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3445 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3446 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003447 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3448 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3449 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003450
3451 dispatchEntry->resolvedFlags = resolvedFlags;
3452 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003453 std::optional<std::vector<PointerProperties>> usingProperties;
3454 std::optional<std::vector<PointerCoords>> usingCoords;
3455 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3456 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3457 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3458 // the dispatcher, and therefore the coordinates of this event are currently
3459 // incorrect. These events should use the coordinates of the last dispatched
3460 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3461 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3462 std::optional<std::pair<std::vector<PointerProperties>,
3463 std::vector<PointerCoords>>>
3464 pointerInfo =
3465 connection->inputState.getPointersOfLastEvent(motionEntry,
3466 hovering);
3467 if (pointerInfo) {
3468 usingProperties = pointerInfo->first;
3469 usingCoords = pointerInfo->second;
3470 }
3471 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003472 // Generate a new MotionEntry with a new eventId using the resolved action and
3473 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003474 resolvedMotion = std::make_shared<
3475 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3476 motionEntry.eventTime, motionEntry.deviceId,
3477 motionEntry.source, motionEntry.displayId,
3478 motionEntry.policyFlags, resolvedAction,
3479 motionEntry.actionButton, resolvedFlags,
3480 motionEntry.metaState, motionEntry.buttonState,
3481 motionEntry.classification, motionEntry.edgeFlags,
3482 motionEntry.xPrecision, motionEntry.yPrecision,
3483 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3484 motionEntry.downTime,
3485 usingProperties.value_or(motionEntry.pointerProperties),
3486 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003487 if (ATRACE_ENABLED()) {
3488 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3489 ") to MotionEvent(id=0x%" PRIx32 ").",
3490 motionEntry.id, resolvedMotion->id);
3491 ATRACE_NAME(message.c_str());
3492 }
3493
3494 // Set the resolved motion entry in the DispatchEntry.
3495 dispatchEntry->eventEntry = resolvedMotion;
3496 eventEntry = resolvedMotion;
3497 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003500 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3501 // devices being active at the same time in the same window, so if a new device is
3502 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003503 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003504 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003505 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003506 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003507 << connection->getInputChannelName() << " with event "
3508 << cancelEvent->getDescription();
3509 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003510 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003511 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003512
3513 // Send these cancel events to the queue before sending the event from the new
3514 // device.
3515 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3516 }
3517
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003518 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003520 LOG(WARNING) << "channel " << connection->getInputChannelName()
3521 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 return; // skip the inconsistent event
3523 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003524 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003525 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003526 // Skip reporting pointer down outside focus to the policy.
3527 break;
3528 }
3529
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003530 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003531 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003532
3533 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003535 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003536 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003537 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3538 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003539 break;
3540 }
Chris Yef59a2f42020-10-16 12:55:26 -07003541 case EventEntry::Type::SENSOR: {
3542 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3543 break;
3544 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003545 case EventEntry::Type::CONFIGURATION_CHANGED:
3546 case EventEntry::Type::DEVICE_RESET: {
3547 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003548 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003549 break;
3550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552
3553 // Remember that we are waiting for this dispatch to complete.
3554 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003555 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557
3558 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003559 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003560 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003561}
3562
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003563/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003564 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003565 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003566 * The first role is to log input interaction with windows, which helps determine what the user was
3567 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3568 * that user started interacting with launcher window, as well as any other window that received
3569 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3570 * when the set of tokens that received the event changes. It is not logged again as long as the
3571 * user is interacting with the same windows.
3572 *
3573 * The second role is to track input device activity for metrics collection. For each input event,
3574 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3575 * input_interaction logs, the device interaction is reported even when the set of interaction
3576 * tokens do not change.
3577 *
3578 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3579 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003581void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3582 const std::vector<InputTarget>& targets) {
3583 int32_t deviceId;
3584 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003585 // Skip ACTION_UP events, and all events other than keys and motions
3586 if (entry.type == EventEntry::Type::KEY) {
3587 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3588 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3589 return;
3590 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003591 deviceId = keyEntry.deviceId;
3592 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 } else if (entry.type == EventEntry::Type::MOTION) {
3594 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3595 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003596 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3597 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003598 return;
3599 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003600 deviceId = motionEntry.deviceId;
3601 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003602 } else {
3603 return; // Not a key or a motion
3604 }
3605
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003606 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003607 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003608 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003609 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003610 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003611 continue; // Skip windows that receive ACTION_OUTSIDE
3612 }
3613
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003614 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003615 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003616 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003617 if (target.windowHandle) {
3618 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3619 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003620 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003621
3622 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3623 REQUIRES(mLock) {
3624 scoped_unlock unlock(mLock);
3625 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3626 };
3627 postCommandLocked(std::move(command));
3628
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003629 if (newConnectionTokens == mInteractionConnectionTokens) {
3630 return; // no change
3631 }
3632 mInteractionConnectionTokens = newConnectionTokens;
3633
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003634 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003635 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003636 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003637 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003638 std::string message = "Interaction with: " + targetList;
3639 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003640 message += "<none>";
3641 }
3642 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3643}
3644
chaviwfd6d3512019-03-25 13:23:49 -07003645void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003646 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003647 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003648 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3649 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003650 return;
3651 }
3652
Vishnu Nairc519ff72021-01-21 08:23:08 -08003653 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003654 if (focusedToken == token) {
3655 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003656 return;
3657 }
3658
Prabir Pradhancef936d2021-07-21 16:17:52 +00003659 auto command = [this, token]() REQUIRES(mLock) {
3660 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003661 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003662 };
3663 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664}
3665
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003666status_t InputDispatcher::publishMotionEvent(Connection& connection,
3667 DispatchEntry& dispatchEntry) const {
3668 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3669 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3670
3671 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003672 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003673
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003674 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003675 // Set the X and Y offset and X and Y scale depending on the input source.
3676 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003677 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003678 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3679 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003680 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003681 scaledCoords[i] = motionEntry.pointerCoords[i];
3682 // Don't apply window scale here since we don't want scale to affect raw
3683 // coordinates. The scale will be sent back to the client and applied
3684 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003685 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003686 }
3687 usingCoords = scaledCoords;
3688 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003689 }
3690
3691 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3692
3693 // Publish the motion event.
3694 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003695 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3696 motionEntry.source, motionEntry.displayId, std::move(hmac),
3697 motionEntry.action, motionEntry.actionButton,
3698 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3699 motionEntry.metaState, motionEntry.buttonState,
3700 motionEntry.classification, dispatchEntry.transform,
3701 motionEntry.xPrecision, motionEntry.yPrecision,
3702 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3703 dispatchEntry.rawTransform, motionEntry.downTime,
3704 motionEntry.eventTime, motionEntry.getPointerCount(),
3705 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003706}
3707
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003709 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003710 ATRACE_NAME_IF(ATRACE_ENABLED(),
3711 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3712 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003713 if (DEBUG_DISPATCH_CYCLE) {
3714 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003717 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003718 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003720 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003721 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722
3723 // Publish the event.
3724 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3726 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003727 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3729 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003731 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3732 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003736 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003737 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3738 keyEntry.deviceId, keyEntry.source,
3739 keyEntry.displayId, std::move(hmac),
3740 keyEntry.action, dispatchEntry->resolvedFlags,
3741 keyEntry.keyCode, keyEntry.scanCode,
3742 keyEntry.metaState, keyEntry.repeatCount,
3743 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003744 if (mTracer) {
3745 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003750 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003751 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003752 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3753 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003754 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003755 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003756 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003757 if (mTracer) {
3758 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3759 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 break;
3761 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003762
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003763 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003765 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003766 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003767 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003768 break;
3769 }
3770
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003771 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3772 const TouchModeEntry& touchModeEntry =
3773 static_cast<const TouchModeEntry&>(eventEntry);
3774 status = connection->inputPublisher
3775 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3776 touchModeEntry.inTouchMode);
3777
3778 break;
3779 }
3780
Prabir Pradhan99987712020-11-10 18:43:05 -08003781 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3782 const auto& captureEntry =
3783 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3784 status = connection->inputPublisher
3785 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003786 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003787 break;
3788 }
3789
arthurhungb89ccb02020-12-30 16:19:01 +08003790 case EventEntry::Type::DRAG: {
3791 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3792 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3793 dragEntry.id, dragEntry.x,
3794 dragEntry.y,
3795 dragEntry.isExiting);
3796 break;
3797 }
3798
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003799 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003800 case EventEntry::Type::DEVICE_RESET:
3801 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003802 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003803 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807
3808 // Check the result.
3809 if (status) {
3810 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003811 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 "This is unexpected because the wait queue is empty, so the pipe "
3814 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003815 "event to it, status=%s(%d)",
3816 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3817 status);
Harry Cutts33476232023-01-30 19:57:29 +00003818 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 } else {
3820 // Pipe is full and we are waiting for the app to finish process some events
3821 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003822 if (DEBUG_DISPATCH_CYCLE) {
3823 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3824 "waiting for the application to catch up",
3825 connection->getInputChannelName().c_str());
3826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828 } else {
3829 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003830 "status=%s(%d)",
3831 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3832 status);
Harry Cutts33476232023-01-30 19:57:29 +00003833 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 return;
3836 }
3837
3838 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003839 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3840 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3841 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003842 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003843 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003844 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003845 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003846 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848}
3849
chaviw09c8d2d2020-08-24 15:48:26 -07003850std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3851 size_t size;
3852 switch (event.type) {
3853 case VerifiedInputEvent::Type::KEY: {
3854 size = sizeof(VerifiedKeyEvent);
3855 break;
3856 }
3857 case VerifiedInputEvent::Type::MOTION: {
3858 size = sizeof(VerifiedMotionEvent);
3859 break;
3860 }
3861 }
3862 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3863 return mHmacKeyManager.sign(start, size);
3864}
3865
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003866const std::array<uint8_t, 32> InputDispatcher::getSignature(
3867 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003868 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003869 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003870 // Only sign events up and down events as the purely move events
3871 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003872 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003873 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003874
3875 VerifiedMotionEvent verifiedEvent =
3876 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3877 verifiedEvent.actionMasked = actionMasked;
3878 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3879 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003880}
3881
3882const std::array<uint8_t, 32> InputDispatcher::getSignature(
3883 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3884 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3885 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003886 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003887}
3888
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003890 const std::shared_ptr<Connection>& connection,
3891 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003892 if (DEBUG_DISPATCH_CYCLE) {
3893 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3894 connection->getInputChannelName().c_str(), seq, toString(handled));
3895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003897 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 return;
3899 }
3900
3901 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003902 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3903 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3904 };
3905 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906}
3907
3908void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003909 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003910 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003911 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003912 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3913 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
3916 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003917 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003918 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003919 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003920 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
3922 // The connection appears to be unrecoverably broken.
3923 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003924 if (connection->status == Connection::Status::NORMAL) {
3925 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
3927 if (notify) {
3928 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003929 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3930 connection->getInputChannelName().c_str());
3931
3932 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003933 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003934 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003935 };
3936 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
3938 }
3939}
3940
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003941void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003942 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003943 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003944 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
3946}
3947
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003948void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003950 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952}
3953
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003954int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3955 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003956 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003957 if (connection == nullptr) {
3958 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3959 connectionToken.get(), events);
3960 return 0; // remove the callback
3961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003963 bool notify;
3964 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3965 if (!(events & ALOOPER_EVENT_INPUT)) {
3966 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3967 "events=0x%x",
3968 connection->getInputChannelName().c_str(), events);
3969 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 }
3971
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003972 nsecs_t currentTime = now();
3973 bool gotOne = false;
3974 status_t status = OK;
3975 for (;;) {
3976 Result<InputPublisher::ConsumerResponse> result =
3977 connection->inputPublisher.receiveConsumerResponse();
3978 if (!result.ok()) {
3979 status = result.error().code();
3980 break;
3981 }
3982
3983 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3984 const InputPublisher::Finished& finish =
3985 std::get<InputPublisher::Finished>(*result);
3986 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3987 finish.consumeTime);
3988 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003989 if (shouldReportMetricsForConnection(*connection)) {
3990 const InputPublisher::Timeline& timeline =
3991 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003992 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3993 connection->getToken(),
3994 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003995 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003996 }
3997 gotOne = true;
3998 }
3999 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004000 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004001 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 return 1;
4003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 }
4005
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004006 notify = status != DEAD_OBJECT || !connection->monitor;
4007 if (notify) {
4008 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4009 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4010 status);
4011 }
4012 } else {
4013 // Monitor channels are never explicitly unregistered.
4014 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004015 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004016 notify = !connection->monitor && stillHaveWindowHandle;
4017 if (notify) {
4018 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4019 connection->getInputChannelName().c_str(), events);
4020 }
4021 }
4022
4023 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004024 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004025 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026}
4027
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004030 // Cancel windows (i.e. non-monitors).
4031 // A channel must have at least one window to receive any input. If a window was removed, the
4032 // event streams directed to the window will already have been canceled during window removal.
4033 // So there is no need to generate cancellations for connections without any windows.
4034 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4035 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4036 // through a non-touched window if there are more than one window for an input channel.
4037 if (cancelPointers) {
4038 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4039 if (options.displayId.has_value() && options.displayId != displayId) {
4040 continue;
4041 }
4042 for (const auto& touchedWindow : touchState.windows) {
4043 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4044 }
4045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004047 // Follow up by generating cancellations for all windows, because we don't explicitly track
4048 // the windows that have an ongoing focus event stream.
4049 if (cancelNonPointers) {
4050 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4051 for (const auto& windowHandle : handles) {
4052 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4053 }
4054 }
4055 }
4056
4057 // Cancel monitors.
4058 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059}
4060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004062 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004063 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004064 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004065 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4066 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004067 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004068 }
4069}
4070
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004071void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4072 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4073 const std::shared_ptr<Connection>& connection) {
4074 if (windowHandle == nullptr) {
4075 LOG(FATAL) << __func__ << ": Window handle must not be null";
4076 }
4077 if (connection) {
4078 // The connection can be optionally provided to avoid multiple lookups.
4079 if (windowHandle->getToken() != connection->getToken()) {
4080 LOG(FATAL) << __func__
4081 << ": Wrong connection provided for window: " << windowHandle->getName();
4082 }
4083 }
4084
4085 std::shared_ptr<Connection> resolvedConnection =
4086 connection ? connection : getConnectionLocked(windowHandle->getToken());
4087 if (!resolvedConnection) {
4088 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4089 return;
4090 }
4091 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4092}
4093
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004095 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4096 const sp<WindowInfoHandle>& window) {
4097 if (!connection->monitor && window == nullptr) {
4098 LOG(FATAL) << __func__
4099 << ": Cannot send event to non-monitor channel without a window - channel: "
4100 << connection->getInputChannelName();
4101 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004102 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 return;
4104 }
4105
4106 nsecs_t currentTime = now();
4107
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004109 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004111 if (cancelationEvents.empty()) {
4112 return;
4113 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004114
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004115 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4116 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004117 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004118 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004119 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004121
Arthur Hungb3307ee2021-10-14 10:57:37 +00004122 std::string reason = std::string("reason=").append(options.reason);
4123 android_log_event_list(LOGTAG_INPUT_CANCEL)
4124 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4125
hongzuo liu95785e22022-09-06 02:51:35 +00004126 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004127 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004128 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004129 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004130
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004131 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004132 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004133 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004134
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004135 switch (cancelationEventEntry->type) {
4136 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004137 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004138 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004139 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4140 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004141 } else {
4142 targets.emplace_back(fallbackTarget);
4143 }
4144 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004147 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004148 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004149 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004150 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004151 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004152 pointerIndex++) {
4153 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4154 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004155 if (mDragState && mDragState->dragWindow->getToken() == token &&
4156 pointerIds.test(mDragState->pointerId)) {
4157 LOG(INFO) << __func__
4158 << ": Canceling drag and drop because the pointers for the drag "
4159 "window are being canceled.";
4160 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4161 mDragState.reset();
4162 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004163 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4164 ftl::Flags<InputTarget::Flags>(), pointerIds,
4165 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004166 } else {
4167 targets.emplace_back(fallbackTarget);
4168 const auto it = mDisplayInfos.find(motionEntry.displayId);
4169 if (it != mDisplayInfos.end()) {
4170 targets.back().displayTransform = it->second.transform;
4171 targets.back().setDefaultPointerTransform(it->second.transform);
4172 }
4173 }
4174 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004177 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004178 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004179 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4180 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004181 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004182 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004183 break;
4184 }
4185 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004186 case EventEntry::Type::DEVICE_RESET:
4187 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004188 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004189 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004190 break;
4191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004194 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004195 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004197
hongzuo liu95785e22022-09-06 02:51:35 +00004198 // If the outbound queue was previously empty, start the dispatch cycle going.
4199 if (wasEmpty && !connection->outboundQueue.empty()) {
4200 startDispatchCycleLocked(currentTime, connection);
4201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202}
4203
Svet Ganov5d3bc372020-01-26 23:11:07 -08004204void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004205 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004206 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004207 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004208 return;
4209 }
4210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004211 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004212 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004213
4214 if (downEvents.empty()) {
4215 return;
4216 }
4217
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004218 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004219 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4220 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004221 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004222
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004223 const auto [_, touchedWindowState, displayId] =
4224 findTouchStateWindowAndDisplayLocked(connection->getToken());
4225 if (touchedWindowState == nullptr) {
4226 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4227 }
4228 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004229
hongzuo liu95785e22022-09-06 02:51:35 +00004230 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004231 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004232 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233 switch (downEventEntry->type) {
4234 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004235 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4236 if (windowHandle != nullptr) {
4237 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004238 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004239 pointerIndex++) {
4240 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4241 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004242 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4243 targetFlags, pointerIds, motionEntry.downTime,
4244 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004245 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004246 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004247 const auto it = mDisplayInfos.find(motionEntry.displayId);
4248 if (it != mDisplayInfos.end()) {
4249 targets.back().displayTransform = it->second.transform;
4250 targets.back().setDefaultPointerTransform(it->second.transform);
4251 }
4252 }
4253 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004254 break;
4255 }
4256
4257 case EventEntry::Type::KEY:
4258 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004259 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004260 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004261 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004262 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004263 case EventEntry::Type::SENSOR:
4264 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004265 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004266 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004267 break;
4268 }
4269 }
4270
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004271 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004272 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004273 }
4274
hongzuo liu95785e22022-09-06 02:51:35 +00004275 // If the outbound queue was previously empty, start the dispatch cycle going.
4276 if (wasEmpty && !connection->outboundQueue.empty()) {
4277 startDispatchCycleLocked(downTime, connection);
4278 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004279}
4280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004282 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4283 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004284 const auto& [action, pointerProperties, pointerCoords] =
4285 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4286 /*historySize=*/0, originalMotionEntry.pointerProperties,
4287 originalMotionEntry.pointerCoords, pointerIds);
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004288 if (pointerIds.count() != pointerCoords.size()) {
4289 // TODO(b/329107108): Determine why some IDs in pointerIds were not in originalMotionEntry.
4290 // This is bad. We are missing some of the pointers that we expected to deliver.
4291 // Most likely this indicates that we received an ACTION_MOVE events that has
4292 // different pointer ids than we expected based on the previous ACTION_DOWN
4293 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4294 // in this way.
4295 ALOGW("Dropping split motion event because the pointer count is %d but "
4296 "we expected there to be %zu pointers. This probably means we received "
4297 "a broken sequence of pointer ids from the input device: %s",
4298 pointerCoords.size(), pointerIds.count(),
4299 originalMotionEntry.getDescription().c_str());
4300 return nullptr;
4301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004303 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4304 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004305 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4306 logDispatchStateLocked();
4307 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4308 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4309 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004310 }
4311
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004312 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004313 ATRACE_NAME_IF(ATRACE_ENABLED(),
4314 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4315 ").",
4316 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004317 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004318 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4319 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320 originalMotionEntry.deviceId, originalMotionEntry.source,
4321 originalMotionEntry.displayId,
4322 originalMotionEntry.policyFlags, action,
4323 originalMotionEntry.actionButton,
4324 originalMotionEntry.flags, originalMotionEntry.metaState,
4325 originalMotionEntry.buttonState,
4326 originalMotionEntry.classification,
4327 originalMotionEntry.edgeFlags,
4328 originalMotionEntry.xPrecision,
4329 originalMotionEntry.yPrecision,
4330 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004331 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004332 pointerProperties, pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 return splitMotionEntry;
4335}
4336
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004337void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4338 std::scoped_lock _l(mLock);
4339 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4340}
4341
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004342void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004343 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004344 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346
Antonio Kantekf16f2832021-09-28 04:39:20 +00004347 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004349 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004351 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004352 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 } // release lock
4355
4356 if (needWake) {
4357 mLooper->wake();
4358 }
4359}
4360
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004361void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004362 ALOGD_IF(debugInboundEventDetails(),
4363 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4364 ", deviceId=%d, source=%s, displayId=%" PRId32
4365 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4366 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4368 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4369 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004370 Result<void> keyCheck = validateKeyEvent(args.action);
4371 if (!keyCheck.ok()) {
4372 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 return;
4374 }
4375
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004376 uint32_t policyFlags = args.policyFlags;
4377 int32_t flags = args.flags;
4378 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004379 // InputDispatcher tracks and generates key repeats on behalf of
4380 // whatever notifies it, so repeatCount should always be set to 0
4381 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4383 policyFlags |= POLICY_FLAG_VIRTUAL;
4384 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 if (policyFlags & POLICY_FLAG_FUNCTION) {
4387 metaState |= AMETA_FUNCTION_ON;
4388 }
4389
4390 policyFlags |= POLICY_FLAG_TRUSTED;
4391
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004392 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004394 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4395 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4396 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397
Michael Wright2b3c3302018-03-02 17:19:13 +00004398 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004399 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004400 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4401 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
Antonio Kantekf16f2832021-09-28 04:39:20 +00004405 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 { // acquire lock
4407 mLock.lock();
4408
4409 if (shouldSendKeyToInputFilterLocked(args)) {
4410 mLock.unlock();
4411
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004412 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004413 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 return; // event was consumed by the filter
4415 }
4416
4417 mLock.lock();
4418 }
4419
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004420 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004421 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4422 args.deviceId, args.source, args.displayId, policyFlags,
4423 args.action, flags, keyCode, args.scanCode, metaState,
4424 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004425 if (mTracer) {
4426 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004429 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 mLock.unlock();
4431 } // release lock
4432
4433 if (needWake) {
4434 mLooper->wake();
4435 }
4436}
4437
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004438bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 return mInputFilterEnabled;
4440}
4441
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004443 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004444 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004445 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004446 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004447 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4448 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004449 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4450 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4451 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4452 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4453 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004454 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004455 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4456 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004457 i, args.pointerProperties[i].id,
4458 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4459 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4460 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4461 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4462 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4463 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4464 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4465 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4466 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4467 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004470
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004471 Result<void> motionCheck =
4472 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4473 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004474 if (!motionCheck.ok()) {
4475 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4476 return;
4477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004479 if (DEBUG_VERIFY_EVENTS) {
4480 auto [it, _] =
4481 mVerifiersByDisplay.try_emplace(args.displayId,
4482 StringPrintf("display %" PRId32, args.displayId));
4483 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004484 it->second.processMovement(args.deviceId, args.source, args.action,
4485 args.getPointerCount(), args.pointerProperties.data(),
4486 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004487 if (!result.ok()) {
4488 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4489 }
4490 }
4491
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004494
4495 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004496 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4497 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004498 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4499 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
Antonio Kantekf16f2832021-09-28 04:39:20 +00004503 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 { // acquire lock
4505 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004506 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4507 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4508 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004509 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004510 if (touchStateIt != mTouchStatesByDisplay.end()) {
4511 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004512 if (touchState.hasTouchingPointers(args.deviceId) ||
4513 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004514 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4515 }
4516 }
4517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518
4519 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004520 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004521 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004522 displayTransform = it->second.transform;
4523 }
4524
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 mLock.unlock();
4526
4527 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004528 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4529 args.action, args.actionButton, args.flags, args.edgeFlags,
4530 args.metaState, args.buttonState, args.classification,
4531 displayTransform, args.xPrecision, args.yPrecision,
4532 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004533 args.downTime, args.eventTime, args.getPointerCount(),
4534 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
4536 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004537 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 return; // event was consumed by the filter
4539 }
4540
4541 mLock.lock();
4542 }
4543
4544 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004545 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004546 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4547 args.deviceId, args.source, args.displayId,
4548 policyFlags, args.action, args.actionButton,
4549 args.flags, args.metaState, args.buttonState,
4550 args.classification, args.edgeFlags, args.xPrecision,
4551 args.yPrecision, args.xCursorPosition,
4552 args.yCursorPosition, args.downTime,
4553 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004554 if (mTracer) {
4555 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004558 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4559 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004560 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004561 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004562 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4563 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4564 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004565 }
4566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 mLock.unlock();
4569 } // release lock
4570
4571 if (needWake) {
4572 mLooper->wake();
4573 }
4574}
4575
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004577 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004578 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4579 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004580 args.id, args.eventTime, args.deviceId, args.source,
4581 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004582 }
Chris Yef59a2f42020-10-16 12:55:26 -07004583
Antonio Kantekf16f2832021-09-28 04:39:20 +00004584 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004585 { // acquire lock
4586 mLock.lock();
4587
4588 // Just enqueue a new sensor event.
4589 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004590 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4591 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4592 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004593
4594 needWake = enqueueInboundEventLocked(std::move(newEntry));
4595 mLock.unlock();
4596 } // release lock
4597
4598 if (needWake) {
4599 mLooper->wake();
4600 }
4601}
4602
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004603void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004604 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004605 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4606 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004607 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004608 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004609}
4610
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004612 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613}
4614
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004615void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004616 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004617 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4618 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004619 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004622 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004624 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625}
4626
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004627void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004628 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004629 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4630 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632
Antonio Kantekf16f2832021-09-28 04:39:20 +00004633 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004635 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004638 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004639 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004640
4641 for (auto& [_, verifier] : mVerifiersByDisplay) {
4642 verifier.resetDevice(args.deviceId);
4643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 } // release lock
4645
4646 if (needWake) {
4647 mLooper->wake();
4648 }
4649}
4650
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004651void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004652 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004653 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4654 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004655 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004656
Antonio Kantekf16f2832021-09-28 04:39:20 +00004657 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004658 { // acquire lock
4659 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004660 auto entry =
4661 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004662 needWake = enqueueInboundEventLocked(std::move(entry));
4663 } // release lock
4664
4665 if (needWake) {
4666 mLooper->wake();
4667 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004668}
4669
Prabir Pradhan5735a322022-04-11 17:23:34 +00004670InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004671 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004672 InputEventInjectionSync syncMode,
4673 std::chrono::milliseconds timeout,
4674 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004675 Result<void> eventValidation = validateInputEvent(*event);
4676 if (!eventValidation.ok()) {
4677 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4678 return InputEventInjectionResult::FAILED;
4679 }
4680
Prabir Pradhan65613802023-02-22 23:36:58 +00004681 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004682 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4683 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4684 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4685 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004686 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004687 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688
Prabir Pradhan5735a322022-04-11 17:23:34 +00004689 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004691 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004692 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4693 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4694 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4695 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4696 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004697 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004698 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004699 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004700 }
4701
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004702 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4703 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004705 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004707 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004708 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004709 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004710 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004711 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4712 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4713 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004714 int32_t keyCode = incomingKey.getKeyCode();
4715 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004716 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004717 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004718 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4719 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4720 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4723 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004724 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725
4726 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4727 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004728 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4730 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4731 std::to_string(t.duration().count()).c_str());
4732 }
4733 }
4734
4735 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004736 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004737 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4738 incomingKey.getEventTime(), resolvedDeviceId,
4739 incomingKey.getSource(), incomingKey.getDisplayId(),
4740 policyFlags, action, flags, keyCode,
4741 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004742 incomingKey.getRepeatCount(),
4743 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004744 if (mTracer) {
4745 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4746 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004747 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 }
4750
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004751 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004752 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004753 const bool isPointerEvent =
4754 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4755 // If a pointer event has no displayId specified, inject it to the default display.
4756 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4757 ? ADISPLAY_ID_DEFAULT
4758 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004759 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760
4761 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004762 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004764 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4765 motionEvent.getAction(), eventTime,
4766 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4768 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4769 std::to_string(t.duration().count()).c_str());
4770 }
4771 }
4772
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004773 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4774 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4775 }
4776
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004778 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004779 const size_t pointerCount = motionEvent.getPointerCount();
4780 const std::vector<PointerProperties>
4781 pointerProperties(motionEvent.getPointerProperties(),
4782 motionEvent.getPointerProperties() + pointerCount);
4783
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004784 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004785 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004786 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4787 *sampleEventTimes, resolvedDeviceId,
4788 motionEvent.getSource(), displayId, policyFlags,
4789 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004790 motionEvent.getActionButton(), flags,
4791 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004792 motionEvent.getButtonState(),
4793 motionEvent.getClassification(),
4794 motionEvent.getEdgeFlags(),
4795 motionEvent.getXPrecision(),
4796 motionEvent.getYPrecision(),
4797 motionEvent.getRawXCursorPosition(),
4798 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004799 motionEvent.getDownTime(), pointerProperties,
4800 std::vector<PointerCoords>(samplePointerCoords,
4801 samplePointerCoords +
4802 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004803 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004804 if (mTracer) {
4805 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4806 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004807 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004808 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004810 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004811 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004812 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4813 resolvedDeviceId, motionEvent.getSource(), displayId,
4814 policyFlags, motionEvent.getAction(),
4815 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004816 motionEvent.getMetaState(), motionEvent.getButtonState(),
4817 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4818 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4819 motionEvent.getRawXCursorPosition(),
4820 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4821 pointerProperties,
4822 std::vector<PointerCoords>(samplePointerCoords,
4823 samplePointerCoords +
4824 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004825 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4826 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004827 if (mTracer) {
4828 nextInjectedEntry->traceTracker =
4829 mTracer->traceInboundEvent(*nextInjectedEntry);
4830 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004831 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 }
4833 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004836 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004837 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004838 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 }
4840
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004842 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004843 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004844 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004845 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004846 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004847 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 }
4849
4850 mLock.unlock();
4851
4852 if (needWake) {
4853 mLooper->wake();
4854 }
4855
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004856 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004858 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004860 if (syncMode == InputEventInjectionSync::NONE) {
4861 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 } else {
4863 for (;;) {
4864 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 break;
4867 }
4868
4869 nsecs_t remainingTimeout = endTime - now();
4870 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004871 if (DEBUG_INJECTION) {
4872 ALOGD("injectInputEvent - Timed out waiting for injection result "
4873 "to become available.");
4874 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 break;
4877 }
4878
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004879 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 }
4881
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004882 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4883 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004885 if (DEBUG_INJECTION) {
4886 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4887 injectionState->pendingForegroundDispatches);
4888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 nsecs_t remainingTimeout = endTime - now();
4890 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004891 if (DEBUG_INJECTION) {
4892 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4893 "dispatches to finish.");
4894 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 break;
4897 }
4898
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004899 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 }
4901 }
4902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 } // release lock
4904
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004905 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004906 LOG(INFO) << "injectInputEvent - Finished with result "
4907 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909
4910 return injectionResult;
4911}
4912
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004913std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004914 std::array<uint8_t, 32> calculatedHmac;
4915 std::unique_ptr<VerifiedInputEvent> result;
4916 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004917 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004918 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4919 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4920 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004921 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004922 break;
4923 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004924 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004925 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4926 VerifiedMotionEvent verifiedMotionEvent =
4927 verifiedMotionEventFromMotionEvent(motionEvent);
4928 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004929 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004930 break;
4931 }
4932 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004933 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004934 return nullptr;
4935 }
4936 }
4937 if (calculatedHmac == INVALID_HMAC) {
4938 return nullptr;
4939 }
tyiu1573a672023-02-21 22:38:32 +00004940 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004941 return nullptr;
4942 }
4943 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004944}
4945
Prabir Pradhan24047542023-11-02 17:14:59 +00004946void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004947 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004948 if (!entry.injectionState) {
4949 // Not an injected event.
4950 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004952
4953 InjectionState& injectionState = *entry.injectionState;
4954 if (DEBUG_INJECTION) {
4955 LOG(INFO) << "Setting input event injection result to "
4956 << ftl::enum_string(injectionResult);
4957 }
4958
4959 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4960 // Log the outcome since the injector did not wait for the injection result.
4961 switch (injectionResult) {
4962 case InputEventInjectionResult::SUCCEEDED:
4963 ALOGV("Asynchronous input event injection succeeded.");
4964 break;
4965 case InputEventInjectionResult::TARGET_MISMATCH:
4966 ALOGV("Asynchronous input event injection target mismatch.");
4967 break;
4968 case InputEventInjectionResult::FAILED:
4969 ALOGW("Asynchronous input event injection failed.");
4970 break;
4971 case InputEventInjectionResult::TIMED_OUT:
4972 ALOGW("Asynchronous input event injection timed out.");
4973 break;
4974 case InputEventInjectionResult::PENDING:
4975 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4976 break;
4977 }
4978 }
4979
4980 injectionState.injectionResult = injectionResult;
4981 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982}
4983
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004984void InputDispatcher::transformMotionEntryForInjectionLocked(
4985 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004986 // Input injection works in the logical display coordinate space, but the input pipeline works
4987 // display space, so we need to transform the injected events accordingly.
4988 const auto it = mDisplayInfos.find(entry.displayId);
4989 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004990 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004991
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004992 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4993 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4994 const vec2 cursor =
4995 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4996 {entry.xCursorPosition, entry.yCursorPosition});
4997 entry.xCursorPosition = cursor.x;
4998 entry.yCursorPosition = cursor.y;
4999 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005000 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005001 entry.pointerCoords[i] =
5002 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5003 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005004 }
5005}
5006
Prabir Pradhan24047542023-11-02 17:14:59 +00005007void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005008 if (entry.injectionState) {
5009 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 }
5011}
5012
Prabir Pradhan24047542023-11-02 17:14:59 +00005013void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005014 if (entry.injectionState) {
5015 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005017 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005018 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 }
5020 }
5021}
5022
chaviw98318de2021-05-19 16:45:23 -05005023const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005024 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005025 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005026 auto it = mWindowHandlesByDisplay.find(displayId);
5027 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005028}
5029
chaviw98318de2021-05-19 16:45:23 -05005030sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005031 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005032 if (windowHandleToken == nullptr) {
5033 return nullptr;
5034 }
5035
Prabir Pradhan16463382023-10-12 23:03:19 +00005036 if (!displayId) {
5037 // Look through all displays.
5038 for (auto& it : mWindowHandlesByDisplay) {
5039 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5040 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5041 if (windowHandle->getToken() == windowHandleToken) {
5042 return windowHandle;
5043 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005046 return nullptr;
5047 }
5048
Prabir Pradhan16463382023-10-12 23:03:19 +00005049 // Only look through the requested display.
5050 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005051 if (windowHandle->getToken() == windowHandleToken) {
5052 return windowHandle;
5053 }
5054 }
5055 return nullptr;
5056}
5057
chaviw98318de2021-05-19 16:45:23 -05005058sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5059 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005060 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005061 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5062 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005063 if (handle->getId() == windowHandle->getId() &&
5064 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005065 if (windowHandle->getInfo()->displayId != it.first) {
5066 ALOGE("Found window %s in display %" PRId32
5067 ", but it should belong to display %" PRId32,
5068 windowHandle->getName().c_str(), it.first,
5069 windowHandle->getInfo()->displayId);
5070 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005071 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 }
5074 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005075 return nullptr;
5076}
5077
chaviw98318de2021-05-19 16:45:23 -05005078sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005079 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5080 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081}
5082
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005083ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5084 auto displayInfoIt = mDisplayInfos.find(displayId);
5085 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5086 : kIdentityTransform;
5087}
5088
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005089bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5090 const MotionEntry& motionEntry) const {
5091 const WindowInfo& info = *window->getInfo();
5092
5093 // Skip spy window targets that are not valid for targeted injection.
5094 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005095 return false;
5096 }
5097
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005098 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5099 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5100 return false;
5101 }
5102
5103 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5104 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5105 window->getName().c_str());
5106 return false;
5107 }
5108
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005109 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005110 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005111 ALOGW("Not sending touch to %s because there's no corresponding connection",
5112 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005113 return false;
5114 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005115
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005116 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005117 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005118 return false;
5119 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005120
5121 // Drop events that can't be trusted due to occlusion
5122 const auto [x, y] = resolveTouchedPosition(motionEntry);
5123 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5124 if (!isTouchTrustedLocked(occlusionInfo)) {
5125 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005126 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005127 for (const auto& log : occlusionInfo.debugInfo) {
5128 ALOGD("%s", log.c_str());
5129 }
5130 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005131 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5132 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005133 return false;
5134 }
5135
5136 // Drop touch events if requested by input feature
5137 if (shouldDropInput(motionEntry, window)) {
5138 return false;
5139 }
5140
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005141 // Ignore touches if stylus is down anywhere on screen
5142 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5143 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5144 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5145 return false;
5146 }
5147
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005148 return true;
5149}
5150
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005151void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005152 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5153 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005154 // Remove all handles on a display if there are no windows left.
5155 mWindowHandlesByDisplay.erase(displayId);
5156 return;
5157 }
5158
5159 // Since we compare the pointer of input window handles across window updates, we need
5160 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005161 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5162 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5163 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005164 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005165 }
5166
chaviw98318de2021-05-19 16:45:23 -05005167 std::vector<sp<WindowInfoHandle>> newHandles;
5168 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005169 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005170 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005172 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005173 const bool canReceiveInput =
5174 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5175 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005176 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005177 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005178 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005179 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005180 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005181 }
5182
5183 if (info->displayId != displayId) {
5184 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5185 handle->getName().c_str(), displayId, info->displayId);
5186 continue;
5187 }
5188
Robert Carredd13602020-04-13 17:24:34 -07005189 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5190 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005191 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005192 oldHandle->updateFrom(handle);
5193 newHandles.push_back(oldHandle);
5194 } else {
5195 newHandles.push_back(handle);
5196 }
5197 }
5198
5199 // Insert or replace
5200 mWindowHandlesByDisplay[displayId] = newHandles;
5201}
5202
Arthur Hungb92218b2018-08-14 12:00:21 +08005203/**
5204 * Called from InputManagerService, update window handle list by displayId that can receive input.
5205 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5206 * If set an empty list, remove all handles from the specific display.
5207 * For focused handle, check if need to change and send a cancel event to previous one.
5208 * For removed handle, check if need to send a cancel event if already in touch.
5209 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005210void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005211 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005212 if (DEBUG_FOCUS) {
5213 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005214 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005215 windowList += iwh->getName() + " ";
5216 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005217 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219
Prabir Pradhand65552b2021-10-07 11:23:50 -07005220 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005221 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005222 const WindowInfo& info = *window->getInfo();
5223
5224 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005225 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005226 if (noInputWindow && window->getToken() != nullptr) {
5227 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5228 window->getName().c_str());
5229 window->releaseChannel();
5230 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005231
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005232 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005233 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5234 !info.inputConfig.test(
5235 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005236 "%s has feature SPY, but is not a trusted overlay.",
5237 window->getName().c_str());
5238
Prabir Pradhand65552b2021-10-07 11:23:50 -07005239 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005240 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5241 !info.inputConfig.test(
5242 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005243 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5244 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005245 }
5246
Arthur Hung72d8dc32020-03-28 00:48:39 +00005247 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005248 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005249 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
chaviw98318de2021-05-19 16:45:23 -05005251 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005252
chaviw98318de2021-05-19 16:45:23 -05005253 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005254
Vishnu Nairc519ff72021-01-21 08:23:08 -08005255 std::optional<FocusResolver::FocusChanges> changes =
5256 mFocusResolver.setInputWindows(displayId, windowHandles);
5257 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005258 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005261 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5262 mTouchStatesByDisplay.find(displayId);
5263 if (stateIt != mTouchStatesByDisplay.end()) {
5264 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005265 for (size_t i = 0; i < state.windows.size();) {
5266 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005267 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005268 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5269 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005270 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5271 "touched window was removed");
5272 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5273 // Since we are about to drop the touch, cancel the events for the wallpaper as
5274 // well.
5275 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5276 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5277 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5278 if (const auto& ww = state.getWallpaperWindow(); ww) {
5279 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005282 state.windows.erase(state.windows.begin() + i);
5283 } else {
5284 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286 }
arthurhungb89ccb02020-12-30 16:19:01 +08005287
arthurhung6d4bed92021-03-17 11:59:33 +08005288 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005289 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005290 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005291 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005292 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005293 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5294 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005295 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005296 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005297 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005298
Arthur Hung72d8dc32020-03-28 00:48:39 +00005299 // Release information for windows that are no longer present.
5300 // This ensures that unused input channels are released promptly.
5301 // Otherwise, they might stick around until the window handle is destroyed
5302 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005303 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005304 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005305 if (DEBUG_FOCUS) {
5306 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005307 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005308 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005309 }
chaviw291d88a2019-02-14 10:33:58 -08005310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311}
5312
5313void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005314 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005315 if (DEBUG_FOCUS) {
5316 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5317 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5318 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005319 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005320 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005321 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 } // release lock
5323
5324 // Wake up poll loop since it may need to make new input dispatching choices.
5325 mLooper->wake();
5326}
5327
Vishnu Nair599f1412021-06-21 10:39:58 -07005328void InputDispatcher::setFocusedApplicationLocked(
5329 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5330 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5331 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5332
5333 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5334 return; // This application is already focused. No need to wake up or change anything.
5335 }
5336
5337 // Set the new application handle.
5338 if (inputApplicationHandle != nullptr) {
5339 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5340 } else {
5341 mFocusedApplicationHandlesByDisplay.erase(displayId);
5342 }
5343
5344 // No matter what the old focused application was, stop waiting on it because it is
5345 // no longer focused.
5346 resetNoFocusedWindowTimeoutLocked();
5347}
5348
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005349void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5350 if (interval.count() < 0) {
5351 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5352 }
5353 std::scoped_lock _l(mLock);
5354 mMinTimeBetweenUserActivityPokes = interval;
5355}
5356
Tiger Huang721e26f2018-07-24 22:26:19 +08005357/**
5358 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5359 * the display not specified.
5360 *
5361 * We track any unreleased events for each window. If a window loses the ability to receive the
5362 * released event, we will send a cancel event to it. So when the focused display is changed, we
5363 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5364 * display. The display-specified events won't be affected.
5365 */
5366void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005367 if (DEBUG_FOCUS) {
5368 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5369 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005370 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005371 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005372
5373 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005374 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005375 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005376 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005377 const auto windowHandle =
5378 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5379 if (windowHandle == nullptr) {
5380 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005381 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005382 CancelationOptions
5383 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5384 "The display which contains this window no longer has focus.");
5385 options.displayId = ADISPLAY_ID_NONE;
5386 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 }
5388 mFocusedDisplayId = displayId;
5389
Chris Ye3c2d6f52020-08-09 10:39:48 -07005390 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005391 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005392 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005393
Vishnu Nairad321cd2020-08-20 16:40:21 -07005394 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005395 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005396 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005397 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005398 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005399 }
5400 }
5401 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005402 } // release lock
5403
5404 // Wake up poll loop since it may need to make new input dispatching choices.
5405 mLooper->wake();
5406}
5407
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005409 if (DEBUG_FOCUS) {
5410 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412
5413 bool changed;
5414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005415 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416
5417 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5418 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 }
5421
5422 if (mDispatchEnabled && !enabled) {
5423 resetAndDropEverythingLocked("dispatcher is being disabled");
5424 }
5425
5426 mDispatchEnabled = enabled;
5427 mDispatchFrozen = frozen;
5428 changed = true;
5429 } else {
5430 changed = false;
5431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 } // release lock
5433
5434 if (changed) {
5435 // Wake up poll loop since it may need to make new input dispatching choices.
5436 mLooper->wake();
5437 }
5438}
5439
5440void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005441 if (DEBUG_FOCUS) {
5442 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444
5445 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005446 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447
5448 if (mInputFilterEnabled == enabled) {
5449 return;
5450 }
5451
5452 mInputFilterEnabled = enabled;
5453 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5454 } // release lock
5455
5456 // Wake up poll loop since there might be work to do to drop everything.
5457 mLooper->wake();
5458}
5459
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005460bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005461 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005462 bool needWake = false;
5463 {
5464 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005465 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005466 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005467 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005468 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5469 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005470 mTouchModePerDisplay.count(displayId) == 0
5471 ? "not set"
5472 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5473
Antonio Kantek15beb512022-06-13 22:35:41 +00005474 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5475 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005476 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005477 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005478 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005479 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5480 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005481 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005482 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005483 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005484 return false;
5485 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005486 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005487 mTouchModePerDisplay[displayId] = inTouchMode;
5488 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5489 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005490 needWake = enqueueInboundEventLocked(std::move(entry));
5491 } // release lock
5492
5493 if (needWake) {
5494 mLooper->wake();
5495 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005496 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005497}
5498
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005499bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005500 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5501 if (focusedToken == nullptr) {
5502 return false;
5503 }
5504 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5505 return isWindowOwnedBy(windowHandle, pid, uid);
5506}
5507
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005508bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005509 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5510 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5511 const sp<WindowInfoHandle> windowHandle =
5512 getWindowHandleLocked(connectionToken);
5513 return isWindowOwnedBy(windowHandle, pid, uid);
5514 }) != mInteractionConnectionTokens.end();
5515}
5516
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005517void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5518 if (opacity < 0 || opacity > 1) {
5519 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5520 return;
5521 }
5522
5523 std::scoped_lock lock(mLock);
5524 mMaximumObscuringOpacityForTouch = opacity;
5525}
5526
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005527std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5528InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005529 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5530 for (TouchedWindow& w : state.windows) {
5531 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005532 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005533 }
5534 }
5535 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005536 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005537}
5538
Prabir Pradhan367f3432024-02-13 23:05:58 +00005539bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5540 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005541 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005542 if (DEBUG_FOCUS) {
5543 ALOGD("Trivial transfer to same window.");
5544 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005545 return true;
5546 }
5547
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550
Arthur Hungabbb9d82021-09-01 14:52:30 +00005551 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005552 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005553
Arthur Hungabbb9d82021-09-01 14:52:30 +00005554 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005555 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 return false;
5557 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005558 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5559 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005560 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5561 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005562 return false;
5563 }
5564 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005565
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005566 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5567 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5568 if (!toWindowHandle) {
5569 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570 return false;
5571 }
5572
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005573 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005574 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005575 touchedWindow->windowHandle->getName().c_str(),
5576 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 }
5578
Arthur Hungabbb9d82021-09-01 14:52:30 +00005579 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005580 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005581 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005582 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583
Arthur Hungabbb9d82021-09-01 14:52:30 +00005584 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005585 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005586 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005587 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005588 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005589 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005590 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005591 // Transferring touch focus using this API should not effect the focused window.
5592 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005593 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005594 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595
Arthur Hungabbb9d82021-09-01 14:52:30 +00005596 // Store the dragging window.
5597 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005598 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005599 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5600 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005601 return false;
5602 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005603 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005604 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005605 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 }
5607
Arthur Hungabbb9d82021-09-01 14:52:30 +00005608 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005609 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5610 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005611 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005612 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005613 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5614 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005615 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005616 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5617 newTargetFlags);
5618
5619 // Check if the wallpaper window should deliver the corresponding event.
5620 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005621 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 } // release lock
5624
5625 // Wake up poll loop since it may need to make new input dispatching choices.
5626 mLooper->wake();
5627 return true;
5628}
5629
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005630/**
5631 * Get the touched foreground window on the given display.
5632 * Return null if there are no windows touched on that display, or if more than one foreground
5633 * window is being touched.
5634 */
5635sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5636 auto stateIt = mTouchStatesByDisplay.find(displayId);
5637 if (stateIt == mTouchStatesByDisplay.end()) {
5638 ALOGI("No touch state on display %" PRId32, displayId);
5639 return nullptr;
5640 }
5641
5642 const TouchState& state = stateIt->second;
5643 sp<WindowInfoHandle> touchedForegroundWindow;
5644 // If multiple foreground windows are touched, return nullptr
5645 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005646 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005647 if (touchedForegroundWindow != nullptr) {
5648 ALOGI("Two or more foreground windows: %s and %s",
5649 touchedForegroundWindow->getName().c_str(),
5650 window.windowHandle->getName().c_str());
5651 return nullptr;
5652 }
5653 touchedForegroundWindow = window.windowHandle;
5654 }
5655 }
5656 return touchedForegroundWindow;
5657}
5658
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005659// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005660bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5661 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005662 sp<IBinder> fromToken;
5663 { // acquire lock
5664 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005665 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005666 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005667 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5668 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005669 return false;
5670 }
5671
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005672 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5673 if (from == nullptr) {
5674 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5675 return false;
5676 }
5677
5678 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005679 } // release lock
5680
Prabir Pradhan367f3432024-02-13 23:05:58 +00005681 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005682}
5683
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005685 if (DEBUG_FOCUS) {
5686 ALOGD("Resetting and dropping all events (%s).", reason);
5687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688
Michael Wrightfb04fd52022-11-24 22:31:11 +00005689 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 synthesizeCancelationEventsForAllConnectionsLocked(options);
5691
5692 resetKeyRepeatLocked();
5693 releasePendingEventLocked();
5694 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005695 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005697 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005698 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699}
5700
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005701void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 dumpDispatchStateLocked(dump);
5704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 std::istringstream stream(dump);
5706 std::string line;
5707
5708 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005709 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711}
5712
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005713std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005714 std::string dump;
5715
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005716 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5717 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005718
5719 std::string windowName = "None";
5720 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005721 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005722 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5723 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5724 : "token has capture without window";
5725 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005726 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005727
5728 return dump;
5729}
5730
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005731void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005732 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5733 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5734 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005735 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736
Tiger Huang721e26f2018-07-24 22:26:19 +08005737 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5738 dump += StringPrintf(INDENT "FocusedApplications:\n");
5739 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5740 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005741 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005742 const std::chrono::duration timeout =
5743 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005744 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005745 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005746 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005749 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005751
Vishnu Nairc519ff72021-01-21 08:23:08 -08005752 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005753 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005755 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005756 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005757 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005758 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5759 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
5761 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005762 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 }
5764
arthurhung6d4bed92021-03-17 11:59:33 +08005765 if (mDragState) {
5766 dump += StringPrintf(INDENT "DragState:\n");
5767 mDragState->dump(dump, INDENT2);
5768 }
5769
Arthur Hungb92218b2018-08-14 12:00:21 +08005770 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005771 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5772 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5773 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5774 const auto& displayInfo = it->second;
5775 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5776 displayInfo.logicalHeight);
5777 displayInfo.transform.dump(dump, "transform", INDENT4);
5778 } else {
5779 dump += INDENT2 "No DisplayInfo found!\n";
5780 }
5781
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005782 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005783 dump += INDENT2 "Windows:\n";
5784 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005785 dump += StringPrintf(INDENT3 "%zu: %s", i,
5786 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005787 }
5788 } else {
5789 dump += INDENT2 "Windows: <none>\n";
5790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005793 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005796 if (!mGlobalMonitorsByDisplay.empty()) {
5797 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5798 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005799 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 }
5804
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005805 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806
5807 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005808 if (!mRecentQueue.empty()) {
5809 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005810 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005811 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005812 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005813 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005816 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
5819 // Dump event currently being dispatched.
5820 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005821 dump += INDENT "PendingEvent:\n";
5822 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005823 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005824 dump += StringPrintf(", age=%" PRId64 "ms\n",
5825 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829
5830 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005831 if (!mInboundQueue.empty()) {
5832 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005833 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005834 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005835 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005836 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005839 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 }
5841
Prabir Pradhancef936d2021-07-21 16:17:52 +00005842 if (!mCommandQueue.empty()) {
5843 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5844 } else {
5845 dump += INDENT "CommandQueue: <empty>\n";
5846 }
5847
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005849 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005850 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005851 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005852 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005853 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005854 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005855 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005856 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005858 if (!connection->outboundQueue.empty()) {
5859 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5860 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005861 dump += dumpQueue(connection->outboundQueue, currentTime);
5862
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005864 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 }
5866
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005867 if (!connection->waitQueue.empty()) {
5868 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5869 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005870 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005872 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005874 std::string inputStateDump = streamableToString(connection->inputState);
5875 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005876 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005877 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
5880 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005881 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 }
5883
Antonio Kantek15beb512022-06-13 22:35:41 +00005884 if (!mTouchModePerDisplay.empty()) {
5885 dump += INDENT "TouchModePerDisplay:\n";
5886 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5887 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5888 std::to_string(touchMode).c_str());
5889 }
5890 } else {
5891 dump += INDENT "TouchModePerDisplay: <none>\n";
5892 }
5893
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005894 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005895 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5896 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5897 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005898 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005899 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005900 dump += INDENT "InputTracer: ";
5901 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902}
5903
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005904void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005905 const size_t numMonitors = monitors.size();
5906 for (size_t i = 0; i < numMonitors; i++) {
5907 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005908 const std::shared_ptr<Connection>& connection = monitor.connection;
5909 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 dump += "\n";
5911 }
5912}
5913
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005914class LooperEventCallback : public LooperCallback {
5915public:
5916 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5917 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5918
5919private:
5920 std::function<int(int events)> mCallback;
5921};
5922
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005923Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005924 if (DEBUG_CHANNEL_CREATION) {
5925 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005928 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005929 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005930 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005931
5932 if (result) {
5933 return base::Error(result) << "Failed to open input channel pair with name " << name;
5934 }
5935
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005937 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005938 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005939 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005940 std::shared_ptr<Connection> connection =
5941 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5942 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005944 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5945 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005946 ALOGE("Created a new connection, but the token %p is already known", token.get());
5947 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005948
5949 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5950 this, std::placeholders::_1, token);
5951
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005952 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005953 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 } // release lock
5955
5956 // Wake the looper because some connections have changed.
5957 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005958 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959}
5960
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005961Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005962 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005963 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005964 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005965 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005966 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005967 if (result) {
5968 return base::Error(result) << "Failed to open input channel pair with name " << name;
5969 }
5970
Michael Wright3dd60e22019-03-27 22:06:44 +00005971 { // acquire lock
5972 std::scoped_lock _l(mLock);
5973
5974 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005975 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5976 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 }
5978
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005979 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005980 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005981 std::shared_ptr<Connection> connection =
5982 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5983 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005984
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005985 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5986 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005987 ALOGE("Created a new connection, but the token %p is already known", token.get());
5988 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005989
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005990 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5991 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005992
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005993 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005994
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005995 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005996 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005997 }
Garfield Tan15601662020-09-22 15:32:38 -07005998
Michael Wright3dd60e22019-03-27 22:06:44 +00005999 // Wake the looper because some connections have changed.
6000 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006001 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006002}
6003
Garfield Tan15601662020-09-22 15:32:38 -07006004status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006006 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007
Harry Cutts33476232023-01-30 19:57:29 +00006008 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 if (status) {
6010 return status;
6011 }
6012 } // release lock
6013
6014 // Wake the poll loop because removing the connection may have changed the current
6015 // synchronization state.
6016 mLooper->wake();
6017 return OK;
6018}
6019
Garfield Tan15601662020-09-22 15:32:38 -07006020status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6021 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006022 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006023 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006024 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025 return BAD_VALUE;
6026 }
6027
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006028 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006029
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006031 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 }
6033
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006034 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035
6036 nsecs_t currentTime = now();
6037 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6038
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006039 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040 return OK;
6041}
6042
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006043void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006044 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6045 auto& [displayId, monitors] = *it;
6046 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006047 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006048 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006049
Michael Wright3dd60e22019-03-27 22:06:44 +00006050 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006051 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006052 } else {
6053 ++it;
6054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 }
6056}
6057
Michael Wright3dd60e22019-03-27 22:06:44 +00006058status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006059 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006060 return pilferPointersLocked(token);
6061}
Michael Wright3dd60e22019-03-27 22:06:44 +00006062
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006063status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006064 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6065 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006066 LOG(WARNING)
6067 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006068 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006069 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006071 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006072 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006073 LOG(WARNING)
6074 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6075 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006076 return BAD_VALUE;
6077 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006078 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006079 if (deviceIds.empty()) {
6080 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006081 return BAD_VALUE;
6082 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006083
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006084 for (const DeviceId deviceId : deviceIds) {
6085 TouchState& state = *statePtr;
6086 TouchedWindow& window = *windowPtr;
6087 // Send cancel events to all the input channels we're stealing from.
6088 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6089 "input channel stole pointer stream");
6090 options.deviceId = deviceId;
6091 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006092 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6093 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006094 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006095
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006096 std::string canceledWindows;
6097 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006098 if (w.windowHandle->getToken() != token) {
6099 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006100 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006101 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006102 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006103 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006104 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006105 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006106 << " is stealing input gesture for device " << deviceId << " from "
6107 << canceledWindows;
6108
6109 // Prevent the gesture from being sent to any other windows.
6110 // This only blocks relevant pointers to be sent to other windows
6111 window.addPilferingPointers(deviceId, pointerIds);
6112
6113 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006114 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006115 return OK;
6116}
6117
Prabir Pradhan99987712020-11-10 18:43:05 -08006118void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6119 { // acquire lock
6120 std::scoped_lock _l(mLock);
6121 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006122 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006123 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6124 windowHandle != nullptr ? windowHandle->getName().c_str()
6125 : "token without window");
6126 }
6127
Vishnu Nairc519ff72021-01-21 08:23:08 -08006128 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006129 if (focusedToken != windowToken) {
6130 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6131 enabled ? "enable" : "disable");
6132 return;
6133 }
6134
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006135 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006136 ALOGW("Ignoring request to %s Pointer Capture: "
6137 "window has %s requested pointer capture.",
6138 enabled ? "enable" : "disable", enabled ? "already" : "not");
6139 return;
6140 }
6141
Christine Franksb768bb42021-11-29 12:11:31 -08006142 if (enabled) {
6143 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6144 mIneligibleDisplaysForPointerCapture.end(),
6145 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6146 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6147 return;
6148 }
6149 }
6150
Prabir Pradhan99987712020-11-10 18:43:05 -08006151 setPointerCaptureLocked(enabled);
6152 } // release lock
6153
6154 // Wake the thread to process command entries.
6155 mLooper->wake();
6156}
6157
Christine Franksb768bb42021-11-29 12:11:31 -08006158void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6159 { // acquire lock
6160 std::scoped_lock _l(mLock);
6161 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6162 if (!isEligible) {
6163 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6164 }
6165 } // release lock
6166}
6167
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006168std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006169 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006170 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006171 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006172 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006173 }
6174 }
6175 }
6176 return std::nullopt;
6177}
6178
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006179std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6180 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006181 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006182 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006183 }
6184
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006185 for (const auto& [token, connection] : mConnectionsByToken) {
6186 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006187 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 }
6189 }
Robert Carr4e670e52018-08-15 13:26:12 -07006190
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006191 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192}
6193
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006194std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006195 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006196 if (connection == nullptr) {
6197 return "<nullptr>";
6198 }
6199 return connection->getInputChannelName();
6200}
6201
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006202void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006203 mAnrTracker.eraseToken(connection->getToken());
6204 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006205}
6206
Prabir Pradhancef936d2021-07-21 16:17:52 +00006207void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006208 const std::shared_ptr<Connection>& connection,
6209 uint32_t seq, bool handled,
6210 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006211 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006212 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006213
6214 { // Start critical section
6215 auto dispatchEntryIt =
6216 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6217 [seq](auto& e) { return e->seq == seq; });
6218 if (dispatchEntryIt == connection->waitQueue.end()) {
6219 return;
6220 }
6221
6222 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6223
6224 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6225 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006226 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006227 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6228 }
6229 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006230 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006231 dispatchEntry.deliveryTime, consumeTime, finishTime);
6232 }
6233
6234 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006235 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6236 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006237 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006238 }
6239 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006240
6241 // Dequeue the event and start the next cycle.
6242 // Because the lock might have been released, it is possible that the
6243 // contents of the wait queue to have been drained, so we need to double-check
6244 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006245 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6246 [seq](auto& e) { return e->seq == seq; });
6247 if (entryIt != connection->waitQueue.end()) {
6248 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6249 connection->waitQueue.erase(entryIt);
6250
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006251 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6253 if (!connection->responsive) {
6254 connection->responsive = isConnectionResponsive(*connection);
6255 if (connection->responsive) {
6256 // The connection was unresponsive, and now it's responsive.
6257 processConnectionResponsiveLocked(*connection);
6258 }
6259 }
6260 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006261 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006262 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6263 // Only dispatch fallbacks if there is a window for the connection.
6264 if (windowHandle != nullptr) {
6265 const auto inputTarget =
6266 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6267 dispatchEntry->targetFlags,
6268 fallbackKeyEntry->downTime);
6269 if (inputTarget.has_value()) {
6270 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6271 *inputTarget);
6272 }
6273 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006275 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006276 }
6277
6278 // Start the next dispatch cycle for this connection.
6279 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280}
6281
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6283 const sp<IBinder>& newToken) {
6284 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6285 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006286 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287 };
6288 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289}
6290
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6292 auto command = [this, token, x, y]() REQUIRES(mLock) {
6293 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006294 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 };
6296 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006297}
6298
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006299void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300 if (connection == nullptr) {
6301 LOG_ALWAYS_FATAL("Caller must check for nullness");
6302 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6304 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006305 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006306 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006307 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006308 return;
6309 }
6310 /**
6311 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6312 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6313 * has changed. This could cause newer entries to time out before the already dispatched
6314 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6315 * processes the events linearly. So providing information about the oldest entry seems to be
6316 * most useful.
6317 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006318 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6319 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320 std::string reason =
6321 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006322 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006324 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006325 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006326 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006327
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6329
6330 // Stop waking up for events on this connection, it is already unresponsive
6331 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006332}
6333
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006334void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6335 std::string reason =
6336 StringPrintf("%s does not have a focused window", application->getName().c_str());
6337 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006338
Yabin Cui8eb9c552023-06-08 18:05:07 +00006339 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006340 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006341 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006342 };
6343 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006344}
6345
chaviw98318de2021-05-19 16:45:23 -05006346void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006347 const std::string& reason) {
6348 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6349 updateLastAnrStateLocked(windowLabel, reason);
6350}
6351
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006352void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6353 const std::string& reason) {
6354 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006355 updateLastAnrStateLocked(windowLabel, reason);
6356}
6357
6358void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6359 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006361 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 struct tm tm;
6363 localtime_r(&t, &tm);
6364 char timestr[64];
6365 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006366 mLastAnrState.clear();
6367 mLastAnrState += INDENT "ANR:\n";
6368 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006369 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6370 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006371 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372}
6373
Prabir Pradhancef936d2021-07-21 16:17:52 +00006374void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006375 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006376 const KeyEvent event = createKeyEvent(entry);
6377 nsecs_t delay = 0;
6378 { // release lock
6379 scoped_unlock unlock(mLock);
6380 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006381 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006382 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6383 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6384 std::to_string(t.duration().count()).c_str());
6385 }
6386 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387
6388 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006389 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006390 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006391 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006393 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006394 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396}
6397
Prabir Pradhancef936d2021-07-21 16:17:52 +00006398void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006399 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006400 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006401 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006402 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006403 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 };
6405 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006406}
6407
Prabir Pradhanedd96402022-02-15 01:46:16 -08006408void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006409 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006410 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006411 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006412 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006413 };
6414 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006415}
6416
6417/**
6418 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6419 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6420 * command entry to the command queue.
6421 */
6422void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6423 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006424 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006425 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006426 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006427 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006428 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006429 pid = findMonitorPidByTokenLocked(connectionToken);
6430 } else {
6431 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006432 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006433 reason.c_str());
6434 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6435 if (handle != nullptr) {
6436 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006437 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006438 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006439 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006440}
6441
6442/**
6443 * Tell the policy that a connection has become responsive so that it can stop ANR.
6444 */
6445void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006446 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006447 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006449 pid = findMonitorPidByTokenLocked(connectionToken);
6450 } else {
6451 // The connection is a window
6452 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6453 if (handle != nullptr) {
6454 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006455 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006456 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006457 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006458}
6459
Prabir Pradhan24047542023-11-02 17:14:59 +00006460std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006461 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006462 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006463 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006464 if (!handled) {
6465 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006466 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006467 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006468 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471 // Get the fallback key state.
6472 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006473 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006475 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 connection->inputState.removeFallbackKey(originalKeyCode);
6477 }
6478
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006479 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 // If the application handles the original key for which we previously
6481 // generated a fallback or if the window is not a foreground window,
6482 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006483 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006484 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006485 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6486 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6487 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6488 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6489 keyEntry.policyFlags);
6490 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006491 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493
6494 mLock.unlock();
6495
Prabir Pradhana41d2442023-04-20 21:30:40 +00006496 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006497 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6498 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006499 unhandledKeyFallback) {
6500 event = *unhandledKeyFallback;
6501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006502
6503 mLock.lock();
6504
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006505 // Cancel the fallback key, but only if we still have a window for the channel.
6506 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006508 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6509 if (windowHandle != nullptr) {
6510 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6511 "application handled the original non-fallback key "
6512 "or is no longer a foreground target, "
6513 "canceling previously dispatched fallback key");
6514 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006515 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006518 connection->inputState.removeFallbackKey(originalKeyCode);
6519 }
6520 } else {
6521 // If the application did not handle a non-fallback key, first check
6522 // that we are in a good state to perform unhandled key event processing
6523 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006524 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006525 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006526 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6527 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6528 "since this is not an initial down. "
6529 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6530 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6531 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006532 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006535 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006536 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6537 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6538 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6539 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6540 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006541 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006542
6543 mLock.unlock();
6544
Prabir Pradhana41d2442023-04-20 21:30:40 +00006545 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006546 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6547 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006548 fb) {
6549 fallback = true;
6550 event = *fb;
6551 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006552
6553 mLock.lock();
6554
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006555 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006557 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558 }
6559
6560 // Latch the fallback keycode for this key on an initial down.
6561 // The fallback keycode cannot change at any other point in the lifecycle.
6562 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006563 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006564 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006565 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006566 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006567 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006568 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006569 }
6570
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006571 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006572
6573 // Cancel the fallback key if the policy decides not to send it anymore.
6574 // We will continue to dispatch the key to the policy but we will no
6575 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006576 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6577 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006578 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6579 if (fallback) {
6580 ALOGD("Unhandled key event: Policy requested to send key %d"
6581 "as a fallback for %d, but on the DOWN it had requested "
6582 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006583 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006584 } else {
6585 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6586 "but on the DOWN it had requested to send %d. "
6587 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006588 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006589 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006590 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006591
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006592 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6593 if (windowHandle != nullptr) {
6594 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6595 "canceling fallback, policy no longer desires it");
6596 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006597 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006598 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006599
6600 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006601 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006602 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006603 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006604 }
6605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006606
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006607 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6608 {
6609 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006610 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006611 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006612 for (const auto& [key, value] : fallbackKeys) {
6613 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006614 }
6615 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6616 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006619
6620 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006621 // Return the fallback key that we want dispatched to the channel.
6622 std::unique_ptr<KeyEntry> newEntry =
6623 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6624 event.getEventTime(), event.getDeviceId(),
6625 event.getSource(), event.getDisplayId(),
6626 keyEntry.policyFlags, keyEntry.action,
6627 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6628 *fallbackKeyCode, event.getScanCode(),
6629 event.getMetaState(), event.getRepeatCount(),
6630 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006631 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6632 ALOGD("Unhandled key event: Dispatching fallback key. "
6633 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006634 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006635 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006636 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006637 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006638 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6639 ALOGD("Unhandled key event: No fallback key.");
6640 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006641
6642 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006643 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006644 }
6645 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006646 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647}
6648
Michael Wrightd02c5b62014-02-10 15:10:22 -08006649void InputDispatcher::traceInboundQueueLengthLocked() {
6650 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006651 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652 }
6653}
6654
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006655void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006656 if (ATRACE_ENABLED()) {
6657 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006658 snprintf(counterName, sizeof(counterName), "oq:%s",
6659 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006660 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006661 }
6662}
6663
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006664void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006665 if (ATRACE_ENABLED()) {
6666 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006667 snprintf(counterName, sizeof(counterName), "wq:%s",
6668 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006669 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670 }
6671}
6672
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006673void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006674 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006676 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006677 dumpDispatchStateLocked(dump);
6678
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006679 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006680 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006681 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006682 }
6683}
6684
6685void InputDispatcher::monitor() {
6686 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006687 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006689 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690}
6691
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006692/**
6693 * Wake up the dispatcher and wait until it processes all events and commands.
6694 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6695 * this method can be safely called from any thread, as long as you've ensured that
6696 * the work you are interested in completing has already been queued.
6697 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006698bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006699 /**
6700 * Timeout should represent the longest possible time that a device might spend processing
6701 * events and commands.
6702 */
6703 constexpr std::chrono::duration TIMEOUT = 100ms;
6704 std::unique_lock lock(mLock);
6705 mLooper->wake();
6706 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6707 return result == std::cv_status::no_timeout;
6708}
6709
Vishnu Naire798b472020-07-23 13:52:21 -07006710/**
6711 * Sets focus to the window identified by the token. This must be called
6712 * after updating any input window handles.
6713 *
6714 * Params:
6715 * request.token - input channel token used to identify the window that should gain focus.
6716 * request.focusedToken - the token that the caller expects currently to be focused. If the
6717 * specified token does not match the currently focused window, this request will be dropped.
6718 * If the specified focused token matches the currently focused window, the call will succeed.
6719 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6720 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6721 * when requesting the focus change. This determines which request gets
6722 * precedence if there is a focus change request from another source such as pointer down.
6723 */
Vishnu Nair958da932020-08-21 17:12:37 -07006724void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6725 { // acquire lock
6726 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006727 std::optional<FocusResolver::FocusChanges> changes =
6728 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6729 if (changes) {
6730 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006731 }
6732 } // release lock
6733 // Wake up poll loop since it may need to make new input dispatching choices.
6734 mLooper->wake();
6735}
6736
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006737void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6738 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006739 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006740 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6741 ? removedFocusedWindowHandle
6742 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6743 if (resolvedWindow == nullptr) {
6744 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006745 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006746 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6747 "focus left window");
6748 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6749 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006750 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006751 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006752 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006753 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006754 }
6755
Prabir Pradhan99987712020-11-10 18:43:05 -08006756 // If a window has pointer capture, then it must have focus. We need to ensure that this
6757 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6758 // If the window loses focus before it loses pointer capture, then the window can be in a state
6759 // where it has pointer capture but not focus, violating the contract. Therefore we must
6760 // dispatch the pointer capture event before the focus event. Since focus events are added to
6761 // the front of the queue (above), we add the pointer capture event to the front of the queue
6762 // after the focus events are added. This ensures the pointer capture event ends up at the
6763 // front.
6764 disablePointerCaptureForcedLocked();
6765
Vishnu Nairc519ff72021-01-21 08:23:08 -08006766 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006767 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006768 }
6769}
Vishnu Nair958da932020-08-21 17:12:37 -07006770
Prabir Pradhan99987712020-11-10 18:43:05 -08006771void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006772 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006773 return;
6774 }
6775
6776 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6777
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006778 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006779 setPointerCaptureLocked(false);
6780 }
6781
6782 if (!mWindowTokenWithPointerCapture) {
6783 // No need to send capture changes because no window has capture.
6784 return;
6785 }
6786
6787 if (mPendingEvent != nullptr) {
6788 // Move the pending event to the front of the queue. This will give the chance
6789 // for the pending event to be dropped if it is a captured event.
6790 mInboundQueue.push_front(mPendingEvent);
6791 mPendingEvent = nullptr;
6792 }
6793
6794 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006795 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006796 mInboundQueue.push_front(std::move(entry));
6797}
6798
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006799void InputDispatcher::setPointerCaptureLocked(bool enable) {
6800 mCurrentPointerCaptureRequest.enable = enable;
6801 mCurrentPointerCaptureRequest.seq++;
6802 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006803 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006804 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006805 };
6806 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006807}
6808
Vishnu Nair599f1412021-06-21 10:39:58 -07006809void InputDispatcher::displayRemoved(int32_t displayId) {
6810 { // acquire lock
6811 std::scoped_lock _l(mLock);
6812 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006813 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006814 setFocusedApplicationLocked(displayId, nullptr);
6815 // Call focus resolver to clean up stale requests. This must be called after input windows
6816 // have been removed for the removed display.
6817 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006818 // Reset pointer capture eligibility, regardless of previous state.
6819 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006820 // Remove the associated touch mode state.
6821 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006822 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006823 } // release lock
6824
6825 // Wake up poll loop since it may need to make new input dispatching choices.
6826 mLooper->wake();
6827}
6828
Patrick Williamsd828f302023-04-28 17:52:08 -05006829void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006830 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6831 {
6832 // acquire lock
6833 std::scoped_lock _l(mLock);
6834 logDispatchStateLocked();
6835 }
6836 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6837 result.error().message().c_str());
6838 };
chaviw15fab6f2021-06-07 14:15:52 -05006839 // The listener sends the windows as a flattened array. Separate the windows by display for
6840 // more convenient parsing.
6841 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006842 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006843 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006844 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006845 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006846
6847 { // acquire lock
6848 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006849
6850 // Ensure that we have an entry created for all existing displays so that if a displayId has
6851 // no windows, we can tell that the windows were removed from the display.
6852 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6853 handlesPerDisplay[displayId];
6854 }
6855
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006856 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006857 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006858 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6859 }
6860
6861 for (const auto& [displayId, handles] : handlesPerDisplay) {
6862 setInputWindowsLocked(handles, displayId);
6863 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006864
6865 if (update.vsyncId < mWindowInfosVsyncId) {
6866 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6867 ", current update vsync id: %" PRId64,
6868 mWindowInfosVsyncId, update.vsyncId);
6869 }
6870 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006871 }
6872 // Wake up poll loop since it may need to make new input dispatching choices.
6873 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006874}
6875
Vishnu Nair062a8672021-09-03 16:07:44 -07006876bool InputDispatcher::shouldDropInput(
6877 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006878 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6879 (windowHandle->getInfo()->inputConfig.test(
6880 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006881 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006882 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6883 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006884 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006885 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006886 windowHandle->getInfo()->displayId);
6887 return true;
6888 }
6889 return false;
6890}
6891
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006892void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006893 const gui::WindowInfosUpdate& update) {
6894 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006895}
6896
Arthur Hungdfd528e2021-12-08 13:23:04 +00006897void InputDispatcher::cancelCurrentTouch() {
6898 {
6899 std::scoped_lock _l(mLock);
6900 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006901 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006902 "cancel current touch");
6903 synthesizeCancelationEventsForAllConnectionsLocked(options);
6904
6905 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006906 }
6907 // Wake up poll loop since there might be work to do.
6908 mLooper->wake();
6909}
6910
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006911void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6912 std::scoped_lock _l(mLock);
6913 mMonitorDispatchingTimeout = timeout;
6914}
6915
Arthur Hungc539dbb2022-12-08 07:45:36 +00006916void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6917 const sp<WindowInfoHandle>& oldWindowHandle,
6918 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006919 TouchState& state, int32_t deviceId,
6920 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006921 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006922 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006923 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6924 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6925 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6926 newWindowHandle->getInfo()->inputConfig.test(
6927 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6928 const sp<WindowInfoHandle> oldWallpaper =
6929 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6930 const sp<WindowInfoHandle> newWallpaper =
6931 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6932 if (oldWallpaper == newWallpaper) {
6933 return;
6934 }
6935
6936 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006937 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006938 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006939 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006940 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006941 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006942 }
6943
6944 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006945 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6946 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006947 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006948 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006949 }
6950}
6951
6952void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6953 ftl::Flags<InputTarget::Flags> newTargetFlags,
6954 const sp<WindowInfoHandle> fromWindowHandle,
6955 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006956 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006957 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006958 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6959 fromWindowHandle->getInfo()->inputConfig.test(
6960 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6961 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6962 toWindowHandle->getInfo()->inputConfig.test(
6963 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6964
6965 const sp<WindowInfoHandle> oldWallpaper =
6966 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6967 const sp<WindowInfoHandle> newWallpaper =
6968 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6969 if (oldWallpaper == newWallpaper) {
6970 return;
6971 }
6972
6973 if (oldWallpaper != nullptr) {
6974 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6975 "transferring touch focus to another window");
6976 state.removeWindowByToken(oldWallpaper->getToken());
6977 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6978 }
6979
6980 if (newWallpaper != nullptr) {
6981 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00006982 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
6983 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006984 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6985 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006986 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006987 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006988 std::shared_ptr<Connection> wallpaperConnection =
6989 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006990 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006991 std::shared_ptr<Connection> toConnection =
6992 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006993 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6994 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6995 wallpaperFlags);
6996 }
6997 }
6998}
6999
7000sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7001 const sp<WindowInfoHandle>& windowHandle) const {
7002 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7003 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7004 bool foundWindow = false;
7005 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7006 if (!foundWindow && otherHandle != windowHandle) {
7007 continue;
7008 }
7009 if (windowHandle == otherHandle) {
7010 foundWindow = true;
7011 continue;
7012 }
7013
7014 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7015 return otherHandle;
7016 }
7017 }
7018 return nullptr;
7019}
7020
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007021void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7022 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007023 std::scoped_lock _l(mLock);
7024
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007025 mConfig.keyRepeatTimeout = timeout.count();
7026 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007027}
7028
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007029bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7030 DeviceId deviceId, int32_t pointerId) {
7031 std::scoped_lock _l(mLock);
7032 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7033 if (touchStateIt == mTouchStatesByDisplay.end()) {
7034 return false;
7035 }
7036 for (const TouchedWindow& window : touchStateIt->second.windows) {
7037 if (window.windowHandle->getToken() == token &&
7038 (window.hasTouchingPointer(deviceId, pointerId) ||
7039 window.hasHoveringPointer(deviceId, pointerId))) {
7040 return true;
7041 }
7042 }
7043 return false;
7044}
7045
Garfield Tane84e6f92019-08-29 17:28:41 -07007046} // namespace android::inputdispatcher