blob: 56b0c8f12c4c9220b91abcd3e888af56cb4e8bf3 [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,
Prabir Pradhana67623c2024-02-21 06:57:36 +0000402 int64_t vsyncId,
403 trace::InputTracerInterface* tracer) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000404 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000405 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
406 const std::optional<int32_t> windowId =
407 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
408 // Assume the only targets that are not associated with a window are global monitors, and use
409 // the system UID for global monitors for tracing purposes.
410 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000411
412 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700413 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700414 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700415 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000416 inputTarget.globalScaleFactor, uid, vsyncId,
417 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000418 }
419
420 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
421 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
422
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000423 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000424
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000425 const ui::Transform* transform = &kIdentityTransform;
426 const ui::Transform* displayTransform = &kIdentityTransform;
427 if (zeroCoords) {
428 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
429 } else {
430 // Use the first pointer information to normalize all other pointers. This could be any
431 // pointer as long as all other pointers are normalized to the same value and the final
432 // DispatchEntry uses the transform for the normalized pointer.
433 transform =
434 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
435 const ui::Transform inverseTransform = transform->inverse();
436 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000437
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000438 // Iterate through all pointers in the event to normalize against the first.
439 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
440 PointerCoords& newCoords = pointerCoords[i];
441 const auto pointerId = motionEntry.pointerProperties[i].id;
442 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000443
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000444 newCoords.copyFrom(motionEntry.pointerCoords[i]);
445 // First, apply the current pointer's transform to update the coordinates into
446 // window space.
447 newCoords.transform(currTransform);
448 // Next, apply the inverse transform of the normalized coordinates so the
449 // current coordinates are transformed into the normalized coordinate space.
450 newCoords.transform(inverseTransform);
451 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000452 }
453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700454 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000455 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000456 motionEntry.eventTime, motionEntry.deviceId,
457 motionEntry.source, motionEntry.displayId,
458 motionEntry.policyFlags, motionEntry.action,
459 motionEntry.actionButton, motionEntry.flags,
460 motionEntry.metaState, motionEntry.buttonState,
461 motionEntry.classification, motionEntry.edgeFlags,
462 motionEntry.xPrecision, motionEntry.yPrecision,
463 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
464 motionEntry.downTime, motionEntry.pointerProperties,
465 pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +0000466 if (tracer) {
467 combinedMotionEntry->traceTracker =
468 tracer->traceDerivedEvent(*combinedMotionEntry, *motionEntry.traceTracker);
469 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000470
471 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700472 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000473 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000474 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000475 return dispatchEntry;
476}
477
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500478template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000479bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500480 if (lhs == nullptr && rhs == nullptr) {
481 return true;
482 }
483 if (lhs == nullptr || rhs == nullptr) {
484 return false;
485 }
486 return *lhs == *rhs;
487}
488
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000489KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000490 KeyEvent event;
491 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
492 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
493 entry.repeatCount, entry.downTime, entry.eventTime);
494 return event;
495}
496
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000498 // Do not keep track of gesture monitors. They receive every event and would disproportionately
499 // affect the statistics.
500 if (connection.monitor) {
501 return false;
502 }
503 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
504 if (!connection.responsive) {
505 return false;
506 }
507 return true;
508}
509
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000510bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000511 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
512 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000513 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
514 return false;
515 }
516 // Only track latency for events that originated from hardware
517 if (eventEntry.isSynthesized()) {
518 return false;
519 }
520 const EventEntry::Type& inputEventEntryType = eventEntry.type;
521 if (inputEventEntryType == EventEntry::Type::KEY) {
522 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
523 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
524 return false;
525 }
526 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
527 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
528 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
529 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
530 return false;
531 }
532 } else {
533 // Not a key or a motion
534 return false;
535 }
536 if (!shouldReportMetricsForConnection(connection)) {
537 return false;
538 }
539 return true;
540}
541
Prabir Pradhancef936d2021-07-21 16:17:52 +0000542/**
543 * Connection is responsive if it has no events in the waitQueue that are older than the
544 * current time.
545 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000546bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000547 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000548 for (const auto& dispatchEntry : connection.waitQueue) {
549 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000550 return false;
551 }
552 }
553 return true;
554}
555
Antonio Kantekf16f2832021-09-28 04:39:20 +0000556// Returns true if the event type passed as argument represents a user activity.
557bool isUserActivityEvent(const EventEntry& eventEntry) {
558 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000559 case EventEntry::Type::CONFIGURATION_CHANGED:
560 case EventEntry::Type::DEVICE_RESET:
561 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000562 case EventEntry::Type::FOCUS:
563 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000564 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000565 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000566 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000567 case EventEntry::Type::KEY:
568 case EventEntry::Type::MOTION:
569 return true;
570 }
571}
572
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800573// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000574bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000575 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800576 const auto inputConfig = windowInfo.inputConfig;
577 if (windowInfo.displayId != displayId ||
578 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800579 return false;
580 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700581 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800582 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800583 return false;
584 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000585
586 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
587 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
588 // the window. Points on the right and bottom edges should not be inside the window, so we need
589 // to be careful about performing a hit test when the display is rotated, since the "right" and
590 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
591 // logical display in which WM determined the bounds. Perform the hit test in the logical
592 // display space to ensure these edges are considered correctly in all orientations.
593 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
594 const auto p = displayTransform.transform(x, y);
595 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800596 return false;
597 }
598 return true;
599}
600
Prabir Pradhand65552b2021-10-07 11:23:50 -0700601bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
602 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000603 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700604}
605
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800606// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000607// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
608// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
609// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800610// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000611bool canReceiveForegroundTouches(const WindowInfo& info) {
612 // A non-touchable window can still receive touch events (e.g. in the case of
613 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
614 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
615}
616
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000617bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700618 if (windowHandle == nullptr) {
619 return false;
620 }
621 const WindowInfo* windowInfo = windowHandle->getInfo();
622 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
623 return true;
624 }
625 return false;
626}
627
Prabir Pradhan5735a322022-04-11 17:23:34 +0000628// Checks targeted injection using the window's owner's uid.
629// Returns an empty string if an entry can be sent to the given window, or an error message if the
630// entry is a targeted injection whose uid target doesn't match the window owner.
631std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
632 const EventEntry& entry) {
633 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
634 // The event was not injected, or the injected event does not target a window.
635 return {};
636 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000637 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000638 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000639 return StringPrintf("No valid window target for injection into uid %s.",
640 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000641 }
642 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000643 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
644 "owned by uid %s.",
645 uid.toString().c_str(), window->getName().c_str(),
646 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000647 }
648 return {};
649}
650
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000651std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700652 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
653 // Always dispatch mouse events to cursor position.
654 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000655 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700656 }
657
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700658 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000659 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
660 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700661}
662
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700663std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
664 if (eventEntry.type == EventEntry::Type::KEY) {
665 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
666 return keyEntry.downTime;
667 } else if (eventEntry.type == EventEntry::Type::MOTION) {
668 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
669 return motionEntry.downTime;
670 }
671 return std::nullopt;
672}
673
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000674/**
675 * Compare the old touch state to the new touch state, and generate the corresponding touched
676 * windows (== input targets).
677 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
678 * If the pointer just entered the new window, produce HOVER_ENTER.
679 * For pointers remaining in the window, produce HOVER_MOVE.
680 */
681std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
682 const TouchState& newTouchState,
683 const MotionEntry& entry) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700685
686 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
687 // ACTION_SCROLL events should not affect the hovering pointer dispatch
688 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000689 }
Linnan Li41859c42024-03-05 16:20:34 +0000690 std::vector<TouchedWindow> out;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000691
692 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800693 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000694
695 std::set<sp<WindowInfoHandle>> oldWindows;
696 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800697 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000698 }
699
700 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800701 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000702
703 // If the pointer is no longer in the new window set, send HOVER_EXIT.
704 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
705 if (newWindows.find(oldWindow) == newWindows.end()) {
706 TouchedWindow touchedWindow;
707 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000708 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000709 out.push_back(touchedWindow);
710 }
711 }
712
713 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
714 TouchedWindow touchedWindow;
715 touchedWindow.windowHandle = newWindow;
716 if (oldWindows.find(newWindow) == oldWindows.end()) {
717 // Any windows that have this pointer now, and didn't have it before, should get
718 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000719 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000720 } else {
721 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700722 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700723 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000724 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
725 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700726 // The Accessibility injected touch exploration event stream
727 // has known inconsistencies, so log ERROR instead of
728 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700729 severity = android::base::LogSeverity::ERROR;
730 }
731 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700732 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000733 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000734 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800735 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000736 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
737 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
738 }
739 out.push_back(touchedWindow);
740 }
741 return out;
742}
743
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800744template <typename T>
745std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
746 left.insert(left.end(), right.begin(), right.end());
747 return left;
748}
749
Harry Cuttsb166c002023-05-09 13:06:05 +0000750// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
751// both.
752void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
753 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
754 if (!window.windowHandle->getInfo()->inputConfig.test(
755 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
756 // In addition to TouchState, erase this window from the input targets! We don't have a
757 // good way to do this today except by adding a nested loop.
758 // TODO(b/282025641): simplify this code once InputTargets are being identified
759 // separately from TouchedWindows.
760 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800761 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000762 });
763 return true;
764 }
765 return false;
766 });
767}
768
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700769/**
770 * In general, touch should be always split between windows. Some exceptions:
771 * 1. Don't split touch if all of the below is true:
772 * (a) we have an active pointer down *and*
773 * (b) a new pointer is going down that's from the same device *and*
774 * (c) the window that's receiving the current pointer does not support split touch.
775 * 2. Don't split mouse events
776 */
777bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
778 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
779 // We should never split mouse events
780 return false;
781 }
782 for (const TouchedWindow& touchedWindow : touchState.windows) {
783 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
784 // Spy windows should not affect whether or not touch is split.
785 continue;
786 }
787 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
788 continue;
789 }
790 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
791 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
792 // Wallpaper window should not affect whether or not touch is split
793 continue;
794 }
795
796 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
797 return false;
798 }
799 }
800 return true;
801}
802
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700803/**
804 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
805 */
806bool isStylusActiveInDisplay(
807 int32_t displayId,
808 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
809 const auto it = touchStatesByDisplay.find(displayId);
810 if (it == touchStatesByDisplay.end()) {
811 return false;
812 }
813 const TouchState& state = it->second;
814 return state.hasActiveStylus();
815}
816
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800817Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
818 struct HashFunction {
819 size_t operator()(const WindowInfo& info) const { return info.id; }
820 };
821
822 std::unordered_set<WindowInfo, HashFunction> windowSet;
823 for (const WindowInfo& info : update.windowInfos) {
824 const auto [_, inserted] = windowSet.insert(info);
825 if (!inserted) {
826 return Error() << "Duplicate entry for " << info;
827 }
828 }
829 return {};
830}
831
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800832int32_t getUserActivityEventType(const EventEntry& eventEntry) {
833 switch (eventEntry.type) {
834 case EventEntry::Type::KEY: {
835 return USER_ACTIVITY_EVENT_BUTTON;
836 }
837 case EventEntry::Type::MOTION: {
838 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
839 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
840 return USER_ACTIVITY_EVENT_TOUCH;
841 }
842 return USER_ACTIVITY_EVENT_OTHER;
843 }
844 default: {
845 LOG_ALWAYS_FATAL("%s events are not user activity",
846 ftl::enum_string(eventEntry.type).c_str());
847 }
848 }
849}
850
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000851std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
852 CancelationOptions::Mode mode) {
853 switch (mode) {
854 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
855 return {true, true};
856 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
857 return {true, false};
858 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
859 return {false, true};
860 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
861 return {false, true};
862 }
863}
864
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000865} // namespace
866
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867// --- InputDispatcher ---
868
Prabir Pradhana41d2442023-04-20 21:30:40 +0000869InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000870 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000871
872InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
873 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700874 : mPolicy(policy),
875 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800877 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800878 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700879 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800880 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700881 mDispatchEnabled(false),
882 mDispatchFrozen(false),
883 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100884 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000885 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800886 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000887 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000888 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700889 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800890 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700892 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700893#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700894 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700895#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700896 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000897
898 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000899 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000900 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800901
902 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903}
904
905InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000906 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
Prabir Pradhancef936d2021-07-21 16:17:52 +0000908 resetKeyRepeatLocked();
909 releasePendingEventLocked();
910 drainInboundQueueLocked();
911 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000913 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700914 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800915 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
917}
918
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700919status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700920 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700921 return ALREADY_EXISTS;
922 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700923 mThread = std::make_unique<InputThread>(
924 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
925 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700926}
927
928status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700929 if (mThread && mThread->isCallingThread()) {
930 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700931 return INVALID_OPERATION;
932 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700933 mThread.reset();
934 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700935}
936
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700938 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800940 std::scoped_lock _l(mLock);
941 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942
943 // Run a dispatch loop if there are no pending commands.
944 // The dispatch loop might enqueue commands to run afterwards.
945 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800946 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 }
948
949 // Run all pending commands if there are any.
950 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000951 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700952 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800954
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700955 // If we are still waiting for ack on some events,
956 // we might have to wake up earlier to check if an app is anr'ing.
957 const nsecs_t nextAnrCheck = processAnrsLocked();
958 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
959
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800960 // We are about to enter an infinitely long sleep, because we have no commands or
961 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700962 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800963 mDispatcherEnteredIdle.notify_all();
964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 } // release lock
966
967 // Wait for callback or timeout or wake. (make sure we round up, not down)
968 nsecs_t currentTime = now();
969 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
970 mLooper->pollOnce(timeoutMillis);
971}
972
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500974 * Raise ANR if there is no focused window.
975 * Before the ANR is raised, do a final state check:
976 * 1. The currently focused application must be the same one we are waiting for.
977 * 2. Ensure we still don't have a focused window.
978 */
979void InputDispatcher::processNoFocusedWindowAnrLocked() {
980 // Check if the application that we are waiting for is still focused.
981 std::shared_ptr<InputApplicationHandle> focusedApplication =
982 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
983 if (focusedApplication == nullptr ||
984 focusedApplication->getApplicationToken() !=
985 mAwaitedFocusedApplication->getApplicationToken()) {
986 // Unexpected because we should have reset the ANR timer when focused application changed
987 ALOGE("Waited for a focused window, but focused application has already changed to %s",
988 focusedApplication->getName().c_str());
989 return; // The focused application has changed.
990 }
991
chaviw98318de2021-05-19 16:45:23 -0500992 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500993 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
994 if (focusedWindowHandle != nullptr) {
995 return; // We now have a focused window. No need for ANR.
996 }
997 onAnrLocked(mAwaitedFocusedApplication);
998}
999
1000/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001001 * Check if any of the connections' wait queues have events that are too old.
1002 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
1003 * Return the time at which we should wake up next.
1004 */
1005nsecs_t InputDispatcher::processAnrsLocked() {
1006 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001007 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001008 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1009 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1010 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001011 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001012 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001013 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001014 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001015 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001016 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001017 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1018 }
1019 }
1020
1021 // Check if any connection ANRs are due
1022 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1023 if (currentTime < nextAnrCheck) { // most likely scenario
1024 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1025 }
1026
1027 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001028 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001029 if (connection == nullptr) {
1030 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1031 return nextAnrCheck;
1032 }
1033 connection->responsive = false;
1034 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001035 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001036 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001037 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038}
1039
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001040std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001041 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001042 if (connection->monitor) {
1043 return mMonitorDispatchingTimeout;
1044 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001045 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001046 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001047 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001048 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001049 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001050}
1051
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001052void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 nsecs_t currentTime = now();
1054
Jeff Browndc5992e2014-04-11 01:27:26 -07001055 // Reset the key repeat timer whenever normal dispatch is suspended while the
1056 // device is in a non-interactive state. This is to ensure that we abort a key
1057 // repeat if the device is just coming out of sleep.
1058 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 resetKeyRepeatLocked();
1060 }
1061
1062 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1063 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001064 if (DEBUG_FOCUS) {
1065 ALOGD("Dispatch frozen. Waiting some more.");
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 return;
1068 }
1069
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 // Ready to start a new event.
1071 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001073 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 // Synthesize a key repeat if appropriate.
1075 if (mKeyRepeatState.lastKeyEntry) {
1076 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1077 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1078 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001079 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081 }
1082
1083 // Nothing to do if there is no pending event.
1084 if (!mPendingEvent) {
1085 return;
1086 }
1087 } else {
1088 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001089 mPendingEvent = mInboundQueue.front();
1090 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 traceInboundQueueLengthLocked();
1092 }
1093
1094 // Poke user activity for this event.
1095 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001096 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 }
1099
1100 // Now we have an event to dispatch.
1101 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001102 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001104 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001106 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001108 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 }
1110
1111 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001112 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 }
1114
1115 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001116 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 const ConfigurationChangedEntry& typedEntry =
1118 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
1122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001125 const DeviceResetEntry& typedEntry =
1126 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 break;
1130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001132 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const FocusEntry> typedEntry =
1134 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001135 dispatchFocusLocked(currentTime, typedEntry);
1136 done = true;
1137 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1138 break;
1139 }
1140
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001141 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001142 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001143 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1144 done = true;
1145 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1146 break;
1147 }
1148
Prabir Pradhan99987712020-11-10 18:43:05 -08001149 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1150 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001151 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001152 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1153 done = true;
1154 break;
1155 }
1156
arthurhungb89ccb02020-12-30 16:19:01 +08001157 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001158 std::shared_ptr<const DragEntry> typedEntry =
1159 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001160 dispatchDragLocked(currentTime, typedEntry);
1161 done = true;
1162 break;
1163 }
1164
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001165 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001166 std::shared_ptr<const KeyEntry> keyEntry =
1167 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001168 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001169 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001171 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1172 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 break;
1176 }
1177
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001178 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001179 std::shared_ptr<const MotionEntry> motionEntry =
1180 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001181 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001182 // The event is stale. However, only drop stale events if there isn't an ongoing
1183 // gesture. That would allow us to complete the processing of the current stroke.
1184 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1185 if (touchStateIt != mTouchStatesByDisplay.end()) {
1186 const TouchState& touchState = touchStateIt->second;
1187 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1188 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1189 dropReason = DropReason::STALE;
1190 }
1191 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001194 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1195 // Only drop events that are focus-dispatched.
1196 dropReason = DropReason::BLOCKED;
1197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
Chris Yef59a2f42020-10-16 12:55:26 -07001202
1203 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001204 std::shared_ptr<const SensorEntry> sensorEntry =
1205 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001206
Chris Yef59a2f42020-10-16 12:55:26 -07001207 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1208 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1209 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1210 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1211 dropReason = DropReason::STALE;
1212 }
1213 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1214 done = true;
1215 break;
1216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218
1219 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001220 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001221 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
Michael Wright3a981722015-06-10 15:26:13 +01001223 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001225 if (mTracer) {
1226 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
1227 mTracer->eventProcessingComplete(*traceTracker);
1228 }
1229 }
1230
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001232 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234}
1235
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001236bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001237 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001238}
1239
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001240/**
1241 * Return true if the events preceding this incoming motion event should be dropped
1242 * Return false otherwise (the default behaviour)
1243 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001244bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001245 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001246 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001247
1248 // Optimize case where the current application is unresponsive and the user
1249 // decides to touch a window in a different application.
1250 // If the application takes too long to catch up then we drop all events preceding
1251 // the touch into the other window.
1252 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001253 const int32_t displayId = motionEntry.displayId;
1254 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001255 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001256
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001257 sp<WindowInfoHandle> touchedWindowHandle =
1258 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001259 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001260 touchedWindowHandle->getApplicationToken() !=
1261 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001262 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001263 ALOGI("Pruning input queue because user touched a different application while waiting "
1264 "for %s",
1265 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001266 return true;
1267 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001268
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001269 // Alternatively, maybe there's a spy window that could handle this event.
1270 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1271 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1272 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001273 const std::shared_ptr<Connection> connection =
1274 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001275 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001276 // This spy window could take more input. Drop all events preceding this
1277 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001278 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001279 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001280 mAwaitedFocusedApplication->getName().c_str());
1281 return true;
1282 }
1283 }
1284 }
1285
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001286 return false;
1287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001290 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001292 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 traceInboundQueueLengthLocked();
1294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001296 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001297 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1298 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001299
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001301 if (mTracer) {
1302 ensureEventTraced(keyEntry);
1303 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001304
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001305 // If a new up event comes in, and the pending event with same key code has been asked
1306 // to try again later because of the policy. We have to reset the intercept key wake up
1307 // time for it may have been handled in the policy and could be dropped.
1308 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1309 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001310 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001311 if (pendingKey.keyCode == keyEntry.keyCode &&
1312 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001313 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1314 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001315 pendingKey.interceptKeyWakeupTime = 0;
1316 needWake = true;
1317 }
1318 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319 break;
1320 }
1321
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001322 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001323 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1324 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001325 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1326 if (mTracer) {
1327 ensureEventTraced(motionEntry);
1328 }
1329 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001330 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001331 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001333
1334 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1335 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1336 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1337 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1338 // and some other events have not yet been processed, the dispatcher will wait for
1339 // these events to be processed before dispatching the key event. This is because
1340 // the unprocessed events may cause the focus to change (for example, by launching a
1341 // new window or tapping a different window). To prevent waiting too long, we force
1342 // the key to be sent to the currently focused window when a new tap comes in.
1343 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1344 "just send the pending key event to the currently focused window.");
1345 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001346 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001347 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001348 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001350 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001351 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1352 break;
1353 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001354 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001355 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001357 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001358 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1359 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001360 // nothing to do
1361 break;
1362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 }
1364
1365 return needWake;
1366}
1367
Prabir Pradhan24047542023-11-02 17:14:59 +00001368void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001369 // Do not store sensor event in recent queue to avoid flooding the queue.
1370 if (entry->type != EventEntry::Type::SENSOR) {
1371 mRecentQueue.push_back(entry);
1372 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001373 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001374 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 }
1376}
1377
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001378sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1379 bool isStylus,
1380 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001382 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001383 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001384 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001385 continue;
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001388 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001389 if (!info.isSpy() &&
1390 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001391 return windowHandle;
1392 }
1393 }
1394 return nullptr;
1395}
1396
1397std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001398 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001399 if (touchedWindow == nullptr) {
1400 return {};
1401 }
1402 // Traverse windows from front to back until we encounter the touched window.
1403 std::vector<InputTarget> outsideTargets;
1404 const auto& windowHandles = getWindowHandlesLocked(displayId);
1405 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1406 if (windowHandle == touchedWindow) {
1407 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1408 // below the touched window will not get ACTION_OUTSIDE event.
1409 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001410 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001411
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001412 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001413 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001414 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1415 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001416 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1417 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001418 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001421 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422}
1423
Prabir Pradhand65552b2021-10-07 11:23:50 -07001424std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001425 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001426 // Traverse windows from front to back and gather the touched spy windows.
1427 std::vector<sp<WindowInfoHandle>> spyWindows;
1428 const auto& windowHandles = getWindowHandlesLocked(displayId);
1429 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1430 const WindowInfo& info = *windowHandle->getInfo();
1431
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001432 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001433 continue;
1434 }
1435 if (!info.isSpy()) {
1436 // The first touched non-spy window was found, so return the spy windows touched so far.
1437 return spyWindows;
1438 }
1439 spyWindows.push_back(windowHandle);
1440 }
1441 return spyWindows;
1442}
1443
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 const char* reason;
1446 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001447 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001448 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001449 ALOGD("Dropped event because policy consumed it.");
1450 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 reason = "inbound event was dropped because the policy consumed it";
1452 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001453 case DropReason::DISABLED:
1454 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 ALOGI("Dropped event because input dispatch is disabled.");
1456 }
1457 reason = "inbound event was dropped because input dispatch is disabled";
1458 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001459 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001460 LOG(INFO) << "Dropping because the current application is not responding and the user "
1461 "has started interacting with a different application: "
1462 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001463 reason = "inbound event was dropped because the current application is not responding "
1464 "and the user has started interacting with a different application";
1465 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001466 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 ALOGI("Dropped event because it is stale.");
1468 reason = "inbound event was dropped because it is stale";
1469 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001470 case DropReason::NO_POINTER_CAPTURE:
1471 ALOGI("Dropped event because there is no window with Pointer Capture.");
1472 reason = "inbound event was dropped because there is no window with Pointer Capture";
1473 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001474 case DropReason::NOT_DROPPED: {
1475 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001481 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001482 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001483 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1484 options.displayId = keyEntry.displayId;
1485 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001489 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1491 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001492 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001493 options.displayId = motionEntry.displayId;
1494 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 synthesizeCancelationEventsForAllConnectionsLocked(options);
1496 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001497 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1498 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001499 options.displayId = motionEntry.displayId;
1500 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 synthesizeCancelationEventsForAllConnectionsLocked(options);
1502 }
1503 break;
1504 }
Chris Yef59a2f42020-10-16 12:55:26 -07001505 case EventEntry::Type::SENSOR: {
1506 break;
1507 }
arthurhungb89ccb02020-12-30 16:19:01 +08001508 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1509 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001510 break;
1511 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001512 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001513 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001514 case EventEntry::Type::CONFIGURATION_CHANGED:
1515 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001516 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001517 break;
1518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520}
1521
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001523 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524}
1525
Prabir Pradhancef936d2021-07-21 16:17:52 +00001526bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001527 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 return false;
1529 }
1530
1531 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001533 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001534 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1535 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001536 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 return true;
1538}
1539
Prabir Pradhancef936d2021-07-21 16:17:52 +00001540void InputDispatcher::postCommandLocked(Command&& command) {
1541 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542}
1543
1544void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001545 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001546 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001547 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 releaseInboundEventLocked(entry);
1549 }
1550 traceInboundQueueLengthLocked();
1551}
1552
1553void InputDispatcher::releasePendingEventLocked() {
1554 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001556 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 }
1558}
1559
Prabir Pradhan24047542023-11-02 17:14:59 +00001560void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001561 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001562 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001563 if (DEBUG_DISPATCH_CYCLE) {
1564 ALOGD("Injected inbound event was dropped.");
1565 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001566 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 }
1568 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001569 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572}
1573
1574void InputDispatcher::resetKeyRepeatLocked() {
1575 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001576 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 }
1578}
1579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001581 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582
Michael Wright2e732952014-09-24 13:26:59 -07001583 uint32_t policyFlags = entry->policyFlags &
1584 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001587 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1588 currentTime, entry->deviceId, entry->source,
1589 entry->displayId, policyFlags, entry->action, entry->flags,
1590 entry->keyCode, entry->scanCode, entry->metaState,
1591 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001594 if (mTracer) {
1595 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1596 }
1597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001598 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601}
1602
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001603bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001604 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001605 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1606 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608
1609 // Reset key repeating in case a keyboard device was added or removed or something.
1610 resetKeyRepeatLocked();
1611
1612 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001613 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1614 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001615 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001616 };
1617 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 return true;
1619}
1620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1622 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1624 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1625 entry.deviceId);
1626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627
liushenxiang42232912021-05-21 20:24:09 +08001628 // Reset key repeating in case a keyboard device was disabled or enabled.
1629 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1630 resetKeyRepeatLocked();
1631 }
1632
Michael Wrightfb04fd52022-11-24 22:31:11 +00001633 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001636
1637 // Remove all active pointers from this device
1638 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1639 touchState.removeAllPointersForDevice(entry.deviceId);
1640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 return true;
1642}
1643
Vishnu Nairad321cd2020-08-20 16:40:21 -07001644void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001645 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001646 if (mPendingEvent != nullptr) {
1647 // Move the pending event to the front of the queue. This will give the chance
1648 // for the pending event to get dispatched to the newly focused window
1649 mInboundQueue.push_front(mPendingEvent);
1650 mPendingEvent = nullptr;
1651 }
1652
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001653 std::unique_ptr<FocusEntry> focusEntry =
1654 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1655 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001656
1657 // This event should go to the front of the queue, but behind all other focus events
1658 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001659 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1660 [](const std::shared_ptr<const EventEntry>& event) {
1661 return event->type == EventEntry::Type::FOCUS;
1662 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001663
1664 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001665 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001666}
1667
Prabir Pradhan24047542023-11-02 17:14:59 +00001668void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1669 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001670 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1671 if (connection == nullptr) {
1672 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001673 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001674 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001675 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001676 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001677 std::string reason = std::string("reason=").append(entry->reason);
1678 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001679 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001680}
1681
Prabir Pradhan99987712020-11-10 18:43:05 -08001682void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001683 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001684 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001685 dropReason = DropReason::NOT_DROPPED;
1686
Prabir Pradhan99987712020-11-10 18:43:05 -08001687 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001688 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001689
1690 if (entry->pointerCaptureRequest.enable) {
1691 // Enable Pointer Capture.
1692 if (haveWindowWithPointerCapture &&
1693 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001694 // This can happen if pointer capture is disabled and re-enabled before we notify the
1695 // app of the state change, so there is no need to notify the app.
1696 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1697 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001698 }
1699 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001700 // This can happen if a window requests capture and immediately releases capture.
1701 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001702 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001703 return;
1704 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001705 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1706 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1707 return;
1708 }
1709
Vishnu Nairc519ff72021-01-21 08:23:08 -08001710 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001711 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1712 mWindowTokenWithPointerCapture = token;
1713 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001714 // Disable Pointer Capture.
1715 // We do not check if the sequence number matches for requests to disable Pointer Capture
1716 // for two reasons:
1717 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1718 // to disable capture with the same sequence number: one generated by
1719 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1720 // Capture being disabled in InputReader.
1721 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1722 // actual Pointer Capture state that affects events being generated by input devices is
1723 // in InputReader.
1724 if (!haveWindowWithPointerCapture) {
1725 // Pointer capture was already forcefully disabled because of focus change.
1726 dropReason = DropReason::NOT_DROPPED;
1727 return;
1728 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001729 token = mWindowTokenWithPointerCapture;
1730 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001731 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001732 setPointerCaptureLocked(false);
1733 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001734 }
1735
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001736 auto connection = getConnectionLocked(token);
1737 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001738 // Window has gone away, clean up Pointer Capture state.
1739 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001740 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001741 setPointerCaptureLocked(false);
1742 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001743 return;
1744 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001745 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001746 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001747
1748 dropReason = DropReason::NOT_DROPPED;
1749}
1750
Prabir Pradhan24047542023-11-02 17:14:59 +00001751void InputDispatcher::dispatchTouchModeChangeLocked(
1752 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001753 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001754 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001755 if (windowHandles.empty()) {
1756 return;
1757 }
1758 const std::vector<InputTarget> inputTargets =
1759 getInputTargetsFromWindowHandlesLocked(windowHandles);
1760 if (inputTargets.empty()) {
1761 return;
1762 }
1763 entry->dispatchInProgress = true;
1764 dispatchEventLocked(currentTime, entry, inputTargets);
1765}
1766
1767std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1768 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1769 std::vector<InputTarget> inputTargets;
1770 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001771 const sp<IBinder>& token = handle->getToken();
1772 if (token == nullptr) {
1773 continue;
1774 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001775 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1776 if (connection == nullptr) {
1777 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001778 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001779 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001780 }
1781 return inputTargets;
1782}
1783
Prabir Pradhan24047542023-11-02 17:14:59 +00001784bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001785 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 if (!entry->dispatchInProgress) {
1788 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1789 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1790 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1791 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001792 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 // We have seen two identical key downs in a row which indicates that the device
1794 // driver is automatically generating key repeats itself. We take note of the
1795 // repeat here, but we disable our own next key repeat timer since it is clear that
1796 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001797 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1798 // Make sure we don't get key down from a different device. If a different
1799 // device Id has same key pressed down, the new device Id will replace the
1800 // current one to hold the key repeat with repeat count reset.
1801 // In the future when got a KEY_UP on the device id, drop it and do not
1802 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1804 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001805 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 } else {
1807 // Not a repeat. Save key down state in case we do see a repeat later.
1808 resetKeyRepeatLocked();
1809 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1810 }
1811 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001812 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1813 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001814 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001815 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001816 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1817 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 resetKeyRepeatLocked();
1820 }
1821
1822 if (entry->repeatCount == 1) {
1823 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1824 } else {
1825 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1826 }
1827
1828 entry->dispatchInProgress = true;
1829
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
1832
1833 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001834 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001836 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 return false; // wait until next wakeup
1838 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001839 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 entry->interceptKeyWakeupTime = 0;
1841 }
1842
1843 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001844 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001846 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001847 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001848
1849 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1850 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1851 };
1852 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001853 // Poke user activity for keys not passed to user
1854 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 return false; // wait for the command to run
1856 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001857 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001859 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001860 if (*dropReason == DropReason::NOT_DROPPED) {
1861 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 }
1863 }
1864
1865 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001866 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001867 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1869 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001870 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001871 // Poke user activity for undispatched keys
1872 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 return true;
1874 }
1875
1876 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001877 InputEventInjectionResult injectionResult;
1878 sp<WindowInfoHandle> focusedWindow =
1879 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1880 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 return false;
1883 }
1884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001885 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 return true;
1888 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001889 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1890
1891 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001892 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1893 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001895 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001898 if (mTracer) {
1899 ensureEventTraced(*entry);
1900 for (const auto& target : inputTargets) {
1901 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1902 }
1903 }
1904
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 // Dispatch the key.
1906 dispatchEventLocked(currentTime, entry, inputTargets);
1907 return true;
1908}
1909
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001910void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001911 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1912 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1913 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1914 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1915 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1916 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1917 entry.metaState, entry.repeatCount, entry.downTime);
1918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919}
1920
Prabir Pradhancef936d2021-07-21 16:17:52 +00001921void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001922 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001923 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1925 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1926 "source=0x%x, sensorType=%s",
1927 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001928 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001929 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001930 auto command = [this, entry]() REQUIRES(mLock) {
1931 scoped_unlock unlock(mLock);
1932
1933 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001934 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001935 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001936 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1937 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001938 };
1939 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001940}
1941
1942bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1944 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001945 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001946 }
Chris Yef59a2f42020-10-16 12:55:26 -07001947 { // acquire lock
1948 std::scoped_lock _l(mLock);
1949
1950 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001951 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001952 if (entry->type == EventEntry::Type::SENSOR) {
1953 it = mInboundQueue.erase(it);
1954 releaseInboundEventLocked(entry);
1955 }
1956 }
1957 }
1958 return true;
1959}
1960
Prabir Pradhan24047542023-11-02 17:14:59 +00001961bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1962 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001963 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001966 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 entry->dispatchInProgress = true;
1968
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001969 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 }
1971
1972 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001973 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001974 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001975 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1976 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 return true;
1978 }
1979
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001980 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
1982 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001983 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001985 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 if (isPointerEvent) {
1987 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001988
1989 if (mDragState &&
1990 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1991 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1992 pilferPointersLocked(mDragState->dragWindow->getToken());
1993 }
1994
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001995 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001996 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001997 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1998 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 } else {
2000 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001 sp<WindowInfoHandle> focusedWindow =
2002 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
2003 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
2004 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002005 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2006 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2007 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002010 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 return false;
2012 }
2013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002014 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002015 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002016 return true;
2017 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002018 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002019 CancelationOptions::Mode mode(
2020 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2021 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002022 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002023 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002024 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 return true;
2026 }
2027
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002028 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002029 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002031 if (mTracer) {
2032 ensureEventTraced(*entry);
2033 for (const auto& target : inputTargets) {
2034 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2035 }
2036 }
2037
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 dispatchEventLocked(currentTime, entry, inputTargets);
2040 return true;
2041}
2042
chaviw98318de2021-05-19 16:45:23 -05002043void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002044 bool isExiting, const int32_t rawX,
2045 const int32_t rawY) {
2046 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002047 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002048 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2049 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002050
2051 enqueueInboundEventLocked(std::move(dragEntry));
2052}
2053
Prabir Pradhan24047542023-11-02 17:14:59 +00002054void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2055 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002056 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2057 if (connection == nullptr) {
2058 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002059 }
arthurhungb89ccb02020-12-30 16:19:01 +08002060 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002061 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002062}
2063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002064void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002065 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002066 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002067 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002068 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002069 "metaState=0x%x, buttonState=0x%x,"
2070 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002071 prefix, entry.eventTime, entry.deviceId,
2072 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2073 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2074 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2075 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002077 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002078 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002079 "x=%f, y=%f, pressure=%f, size=%f, "
2080 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2081 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002082 i, entry.pointerProperties[i].id,
2083 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002084 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2085 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2086 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2087 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2088 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2089 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2090 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2091 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2092 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095}
2096
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002097void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002098 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002099 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002101 if (DEBUG_DISPATCH_CYCLE) {
2102 ALOGD("dispatchEventToCurrentInputTargets");
2103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002105 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002106
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002109 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002111 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002112 std::shared_ptr<Connection> connection = inputTarget.connection;
2113 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
2115}
2116
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002117void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2119 // If the policy decides to close the app, we will get a channel removal event via
2120 // unregisterInputChannel, and will clean up the connection that way. We are already not
2121 // sending new pointers to the connection when it blocked, but focused events will continue to
2122 // pile up.
2123 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002124 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002125 if (connection->status != Connection::Status::NORMAL) {
2126 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002128 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2129 "application not responding");
2130
2131 sp<WindowInfoHandle> windowHandle;
2132 if (!connection->monitor) {
2133 windowHandle = getWindowHandleLocked(connection->getToken());
2134 if (windowHandle == nullptr) {
2135 // The window that is receiving this ANR was removed, so there is no need to generate
2136 // cancellations, because the cancellations would have already been generated when
2137 // the window was removed.
2138 return;
2139 }
2140 }
2141 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142}
2143
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002144void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002145 if (DEBUG_FOCUS) {
2146 ALOGD("Resetting ANR timeouts.");
2147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
2149 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002151 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152}
2153
Tiger Huang721e26f2018-07-24 22:26:19 +08002154/**
2155 * Get the display id that the given event should go to. If this event specifies a valid display id,
2156 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2157 * Focused display is the display that the user most recently interacted with.
2158 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002160 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002161 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002162 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2164 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 break;
2166 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002167 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2169 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170 break;
2171 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002172 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002173 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002174 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002175 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002176 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002177 case EventEntry::Type::SENSOR:
2178 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002179 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 return ADISPLAY_ID_NONE;
2181 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002182 }
2183 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2184}
2185
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2187 const char* focusedWindowName) {
2188 if (mAnrTracker.empty()) {
2189 // already processed all events that we waited for
2190 mKeyIsWaitingForEventsTimeout = std::nullopt;
2191 return false;
2192 }
2193
2194 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2195 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002196 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002197 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002198 std::chrono::duration_cast<std::chrono::nanoseconds>(
2199 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002200 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 return true;
2202 }
2203
2204 // We still have pending events, and already started the timer
2205 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2206 return true; // Still waiting
2207 }
2208
2209 // Waited too long, and some connection still hasn't processed all motions
2210 // Just send the key to the focused window
2211 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2212 focusedWindowName);
2213 mKeyIsWaitingForEventsTimeout = std::nullopt;
2214 return false;
2215}
2216
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002218 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002219 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002220 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221
Tiger Huang721e26f2018-07-24 22:26:19 +08002222 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002223 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002224 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002225 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2226
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 // If there is no currently focused window and no focused application
2228 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2230 ALOGI("Dropping %s event because there is no focused window or focused application in "
2231 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002232 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002233 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235
Vishnu Nair062a8672021-09-03 16:07:44 -07002236 // Drop key events if requested by input feature
2237 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002238 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002239 }
2240
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2242 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2243 // start interacting with another application via touch (app switch). This code can be removed
2244 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2245 // an app is expected to have a focused window.
2246 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2247 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2248 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002249 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2250 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2251 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002252 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002253 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002254 ALOGW("Waiting because no window has focus but %s may eventually add a "
2255 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002256 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002257 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002258 outInjectionResult = InputEventInjectionResult::PENDING;
2259 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2261 // Already raised ANR. Drop the event
2262 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002263 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002264 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002265 } else {
2266 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002267 outInjectionResult = InputEventInjectionResult::PENDING;
2268 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269 }
2270 }
2271
2272 // we have a valid, non-null focused window
2273 resetNoFocusedWindowTimeoutLocked();
2274
Prabir Pradhan5735a322022-04-11 17:23:34 +00002275 // Verify targeted injection.
2276 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2277 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002278 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2279 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
2281
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002282 if (focusedWindowHandle->getInfo()->inputConfig.test(
2283 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002284 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002285 outInjectionResult = InputEventInjectionResult::PENDING;
2286 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002287 }
2288
2289 // If the event is a key event, then we must wait for all previous events to
2290 // complete before delivering it because previous events may have the
2291 // side-effect of transferring focus to a different window and we want to
2292 // ensure that the following keys are sent to the new window.
2293 //
2294 // Suppose the user touches a button in a window then immediately presses "A".
2295 // If the button causes a pop-up window to appear then we want to ensure that
2296 // the "A" key is delivered to the new pop-up window. This is because users
2297 // often anticipate pending UI changes when typing on a keyboard.
2298 // To obtain this behavior, we must serialize key events with respect to all
2299 // prior input events.
2300 if (entry.type == EventEntry::Type::KEY) {
2301 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002302 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002303 outInjectionResult = InputEventInjectionResult::PENDING;
2304 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002308 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2309 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310}
2311
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002312/**
2313 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2314 * that are currently unresponsive.
2315 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002316std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2317 const std::vector<Monitor>& monitors) const {
2318 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002319 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002320 [](const Monitor& monitor) REQUIRES(mLock) {
2321 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002322 if (!connection->responsive) {
2323 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002324 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002325 return false;
2326 }
2327 return true;
2328 });
2329 return responsiveMonitors;
2330}
2331
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002332std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002333 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002334 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002337 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 // For security reasons, we defer updating the touch state until we are sure that
2339 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002340 const int32_t displayId = entry.displayId;
2341 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002342 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
2344 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002345 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002347 // Copy current touch state into tempTouchState.
2348 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2349 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002350 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002351 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002352 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2353 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002354 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002355 }
2356
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002357 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002358
2359 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2360 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2361 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002362 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2363 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002364 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002365 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2366 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002367 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2368 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2369 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002370 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002371
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002372 if (newGesture) {
2373 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002374 }
2375
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002376 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2377 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2378 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 }
2380
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002381 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002382 if (wasDown) {
2383 // Started hovering, but the device is already down: reject the hover event
2384 LOG(ERROR) << "Got hover event " << entry.getDescription()
2385 << " but the device is already down " << oldState->dump();
2386 outInjectionResult = InputEventInjectionResult::FAILED;
2387 return {};
2388 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002389 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2390 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002391 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002392 }
2393
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2395 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002396 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002397 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002398 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002399 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2400 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002401 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002402 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002403 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002404
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002405 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002406 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002409 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002410 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002412 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002413 }
2414
Prabir Pradhan5735a322022-04-11 17:23:34 +00002415 // Verify targeted injection.
2416 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2417 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002418 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002419 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002420 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002421 }
2422
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002424 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2426 // New window supports splitting, but we should never split mouse events.
2427 isSplit = !isFromMouse;
2428 } else if (isSplit) {
2429 // New window does not support splitting but we have already split events.
2430 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002431 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2432 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002433 newTouchedWindowHandle = nullptr;
2434 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002435 } else {
2436 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002437 // be delivered to a new window which supports split touch. Pointers from a mouse device
2438 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002439 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002440 }
2441
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002442 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002443 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002444 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002445 // Process the foreground window first so that it is the first to receive the event.
2446 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002447 }
2448
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002449 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002450 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2451 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002452 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002453 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002454 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002455 }
2456
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002457 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002458 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002459 continue;
2460 }
2461
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002462 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002463 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002464 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002465 }
2466
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002467 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002468 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002469
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002470 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2471 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002472 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002473 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002474
2475 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002476 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002477 }
2478 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002479 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002480 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002481 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002482 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002483
2484 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002485
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002486 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002487 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2488 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002489 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002490 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002491 isDownOrPointerDown
2492 ? std::make_optional(entry.eventTime)
2493 : std::nullopt);
2494 // If this is the pointer going down and the touched window has a wallpaper
2495 // then also add the touched wallpaper windows so they are locked in for the
2496 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2497 // SCROLL because the wallpaper engine only supports touch events. We would need to
2498 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2499 // handle these events.
2500 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002501 windowHandle->getInfo()->inputConfig.test(
2502 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2503 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2504 if (wallpaper != nullptr) {
2505 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2506 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002507 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002508 if (isSplit) {
2509 wallpaperFlags |= InputTarget::Flags::SPLIT;
2510 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002511 tempTouchState.addOrUpdateWindow(wallpaper,
2512 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002513 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002514 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002515 }
2516 }
2517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002519
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002520 // If a window is already pilfering some pointers, give it this new pointer as well and
2521 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2522 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002523 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002524 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002525 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002526 // This window is already pilfering some pointers, and this new pointer is also
2527 // going to it. Therefore, take over this pointer and don't give it to anyone
2528 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002529 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002530 }
2531 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002532
2533 // Restrict all pilfered pointers to the pilfering windows.
2534 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 } else {
2536 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2537
2538 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002539 if (!tempTouchState.isDown(entry.deviceId) &&
2540 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002541 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2542 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2543 << " is not down or we previously dropped the pointer down event in "
2544 << "display " << displayId << ": " << entry.getDescription();
2545 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002546 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002547 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002550 // If the pointer is not currently hovering, then ignore the event.
2551 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2552 const int32_t pointerId = entry.pointerProperties[0].id;
2553 if (oldState == nullptr ||
2554 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2555 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2556 "display "
2557 << displayId << ": " << entry.getDescription();
2558 outInjectionResult = InputEventInjectionResult::FAILED;
2559 return {};
2560 }
2561 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2562 }
2563
arthurhung6d4bed92021-03-17 11:59:33 +08002564 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002565
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002567 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002568 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002569 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002570 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002571 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002572 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002573 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002574 sp<WindowInfoHandle> newTouchedWindowHandle =
2575 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002576
Prabir Pradhan5735a322022-04-11 17:23:34 +00002577 // Verify targeted injection.
2578 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2579 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002580 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002581 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002582 }
2583
Linnan Libf069a32024-02-29 17:22:59 +00002584 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002585 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002586 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002587 newTouchedWindowHandle = nullptr;
2588 }
2589
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002590 if (newTouchedWindowHandle != nullptr &&
2591 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002592 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002593 oldTouchedWindowHandle->getName().c_str(),
2594 newTouchedWindowHandle->getName().c_str(), displayId);
2595
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002597 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002598 const PointerProperties& pointer = entry.pointerProperties[0];
2599 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002600
2601 const TouchedWindow& touchedWindow =
2602 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002603 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002604 InputTarget::DispatchMode::SLIPPERY_EXIT,
2605 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002606 touchedWindow.getDownTimeInTarget(entry.deviceId),
2607 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608
2609 // Make a slippery entrance into the new window.
2610 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002611 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 }
2613
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002614 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002615 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002616 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002619 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002622 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002623 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002624 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 }
2626
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002627 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2628 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002629 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002630 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002631
2632 // Check if the wallpaper window should deliver the corresponding event.
2633 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002634 tempTouchState, entry.deviceId, pointer, targets);
2635 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002636 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
2638 }
Arthur Hung96483742022-11-15 03:30:48 +00002639
2640 // Update the pointerIds for non-splittable when it received pointer down.
2641 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2642 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002643 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002644 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2645 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002646 // Ignore drag window for it should just track one pointer.
2647 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2648 continue;
2649 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002650 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002651 }
2652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002655 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002656 {
2657 std::vector<TouchedWindow> hoveringWindows =
2658 getHoveringWindowsLocked(oldState, tempTouchState, entry);
Linnan Li41859c42024-03-05 16:20:34 +00002659 // Hardcode to single hovering pointer for now.
2660 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2661 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002662 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002663 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2664 touchedWindow.targetFlags, pointerIds,
2665 touchedWindow.getDownTimeInTarget(entry.deviceId),
2666 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669
Prabir Pradhan5735a322022-04-11 17:23:34 +00002670 // Ensure that all touched windows are valid for injection.
2671 if (entry.injectionState != nullptr) {
2672 std::string errs;
2673 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002674 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2675 if (err) errs += "\n - " + *err;
2676 }
2677 if (!errs.empty()) {
2678 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002679 "%s:%s",
2680 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002681 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002682 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002683 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002684 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002685
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002686 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2687 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002689 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002690 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002691 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002692 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002693 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002694 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002695 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002696 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002697 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2698 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 }
2701 }
2702 }
2703 }
2704
Harry Cuttsb166c002023-05-09 13:06:05 +00002705 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2706 // only want the system UI to handle these gestures.
2707 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2708 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2709 if (isTouchpadNavGesture) {
2710 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2711 }
2712
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002713 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002714 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002715 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002716 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002717 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002718 continue;
2719 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002720 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002721 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002722 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002723 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002724
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002725 // During targeted injection, only allow owned targets to receive events
2726 std::erase_if(targets, [&](const InputTarget& target) {
2727 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2728 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2729 if (err) {
2730 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2731 << ": " << (*err);
2732 return true;
2733 }
2734 return false;
2735 });
2736
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002737 if (targets.empty()) {
2738 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2739 outInjectionResult = InputEventInjectionResult::FAILED;
2740 return {};
2741 }
2742
2743 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2744 // window that is actually receiving the entire gesture.
2745 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002746 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002747 })) {
2748 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2749 << entry.getDescription();
2750 outInjectionResult = InputEventInjectionResult::FAILED;
2751 return {};
2752 }
2753
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002754 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
Prabir Pradhan502a7252023-12-01 16:11:24 +00002756 // Now that we have generated all of the input targets for this event, reset the dispatch
2757 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002758 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002759 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002760 }
2761
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002762 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002763 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002764 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002765 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002766 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002767 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002768 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002769 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2770 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002771 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2772 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2773 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 }
2775
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002776 // Save changes unless the action was scroll in which case the temporary touch
2777 // state was only valid for this one action.
2778 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002779 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002780 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002781 mTouchStatesByDisplay[displayId] = tempTouchState;
2782 } else {
2783 mTouchStatesByDisplay.erase(displayId);
2784 }
2785 }
2786
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002787 if (tempTouchState.windows.empty()) {
2788 mTouchStatesByDisplay.erase(displayId);
2789 }
2790
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002791 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792}
2793
arthurhung6d4bed92021-03-17 11:59:33 +08002794void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002795 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2796 // have an explicit reason to support it.
2797 constexpr bool isStylus = false;
2798
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002799 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002800 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002801 if (dropWindow) {
2802 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002803 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002804 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002805 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002806 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002807 }
2808 mDragState.reset();
2809}
2810
2811void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002812 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002813 return;
2814 }
2815
arthurhung6d4bed92021-03-17 11:59:33 +08002816 if (!mDragState->isStartDrag) {
2817 mDragState->isStartDrag = true;
2818 mDragState->isStylusButtonDownAtStart =
2819 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2820 }
2821
Arthur Hung54745652022-04-20 07:17:41 +00002822 // Find the pointer index by id.
2823 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002824 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002825 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2826 if (pointerProperties.id == mDragState->pointerId) {
2827 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002828 }
Arthur Hung54745652022-04-20 07:17:41 +00002829 }
arthurhung6d4bed92021-03-17 11:59:33 +08002830
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002831 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002832 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002833 }
2834
2835 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2836 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2837 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2838
2839 switch (maskedAction) {
2840 case AMOTION_EVENT_ACTION_MOVE: {
2841 // Handle the special case : stylus button no longer pressed.
2842 bool isStylusButtonDown =
2843 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2844 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2845 finishDragAndDrop(entry.displayId, x, y);
2846 return;
2847 }
2848
2849 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2850 // until we have an explicit reason to support it.
2851 constexpr bool isStylus = false;
2852
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002853 sp<WindowInfoHandle> hoverWindowHandle =
2854 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2855 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002856 // enqueue drag exit if needed.
2857 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2858 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2859 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002860 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002861 y);
2862 }
2863 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2864 }
2865 // enqueue drag location if needed.
2866 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002867 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002868 }
2869 break;
2870 }
2871
2872 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002873 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002874 break;
2875 }
2876 // The drag pointer is up.
2877 [[fallthrough]];
2878 case AMOTION_EVENT_ACTION_UP:
2879 finishDragAndDrop(entry.displayId, x, y);
2880 break;
2881 case AMOTION_EVENT_ACTION_CANCEL: {
2882 ALOGD("Receiving cancel when drag and drop.");
2883 sendDropWindowCommandLocked(nullptr, 0, 0);
2884 mDragState.reset();
2885 break;
2886 }
arthurhungb89ccb02020-12-30 16:19:01 +08002887 }
2888}
2889
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002890std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2891 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002892 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002893 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002894 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2895 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002896 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2897 return {};
2898 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002899 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002900 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002901 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002902 inputTarget.flags = targetFlags;
2903 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2904 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2905 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2906 if (displayInfoIt != mDisplayInfos.end()) {
2907 inputTarget.displayTransform = displayInfoIt->second.transform;
2908 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002909 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002910 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2911 }
2912 return inputTarget;
2913}
2914
chaviw98318de2021-05-19 16:45:23 -05002915void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002916 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002917 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002918 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002919 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002920 std::vector<InputTarget>::iterator it =
2921 std::find_if(inputTargets.begin(), inputTargets.end(),
2922 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002923 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002924 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002925
chaviw98318de2021-05-19 16:45:23 -05002926 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002927
2928 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002929 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002930 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2931 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002932 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002933 return;
2934 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002935 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002936 it = inputTargets.end() - 1;
2937 }
2938
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002939 if (it->flags != targetFlags) {
2940 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2941 }
2942 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2943 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2944 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2945 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002946}
2947
2948void InputDispatcher::addPointerWindowTargetLocked(
2949 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002950 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2951 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2952 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002953 if (pointerIds.none()) {
2954 for (const auto& target : inputTargets) {
2955 LOG(INFO) << "Target: " << target;
2956 }
2957 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2958 return;
2959 }
2960 std::vector<InputTarget>::iterator it =
2961 std::find_if(inputTargets.begin(), inputTargets.end(),
2962 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002963 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002964 });
2965
2966 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2967 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2968 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2969 // input targets for hovering pointers and for touching pointers.
2970 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2971 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002972 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002973 // Force the code below to create a new input target
2974 it = inputTargets.end();
2975 }
2976
2977 const WindowInfo* windowInfo = windowHandle->getInfo();
2978
2979 if (it == inputTargets.end()) {
2980 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002981 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2982 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002983 if (!target) {
2984 return;
2985 }
2986 inputTargets.push_back(*target);
2987 it = inputTargets.end() - 1;
2988 }
2989
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002990 if (it->dispatchMode != dispatchMode) {
2991 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2992 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2993 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002994 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002995 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2996 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002997 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002998 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002999 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003000 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3001 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003002
chaviw1ff3d1e2020-07-01 15:53:47 -07003003 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004}
3005
Michael Wright3dd60e22019-03-27 22:06:44 +00003006void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07003007 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003008 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3009 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003010
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003011 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003012 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003013 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3014 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003015 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3016 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003017 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003018 target.setDefaultPointerTransform(target.displayTransform);
3019 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 }
3021}
3022
Robert Carrc9bf1d32020-04-13 17:21:08 -07003023/**
3024 * Indicate whether one window handle should be considered as obscuring
3025 * another window handle. We only check a few preconditions. Actually
3026 * checking the bounds is left to the caller.
3027 */
chaviw98318de2021-05-19 16:45:23 -05003028static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3029 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003030 // Compare by token so cloned layers aren't counted
3031 if (haveSameToken(windowHandle, otherHandle)) {
3032 return false;
3033 }
3034 auto info = windowHandle->getInfo();
3035 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003036 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003037 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003038 } else if (otherInfo->alpha == 0 &&
3039 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003040 // Those act as if they were invisible, so we don't need to flag them.
3041 // We do want to potentially flag touchable windows even if they have 0
3042 // opacity, since they can consume touches and alter the effects of the
3043 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003044 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003045 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3046 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003047 } else if (info->ownerUid == otherInfo->ownerUid) {
3048 // If ownerUid is the same we don't generate occlusion events as there
3049 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003050 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003051 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003052 return false;
3053 } else if (otherInfo->displayId != info->displayId) {
3054 return false;
3055 }
3056 return true;
3057}
3058
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003059/**
3060 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3061 * untrusted, one should check:
3062 *
3063 * 1. If result.hasBlockingOcclusion is true.
3064 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3065 * BLOCK_UNTRUSTED.
3066 *
3067 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3068 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3069 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3070 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3071 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3072 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3073 *
3074 * If neither of those is true, then it means the touch can be allowed.
3075 */
3076InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003077 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3078 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003079 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003080 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003081 TouchOcclusionInfo info;
3082 info.hasBlockingOcclusion = false;
3083 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003084 info.obscuringUid = gui::Uid::INVALID;
3085 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003086 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003087 if (windowHandle == otherHandle) {
3088 break; // All future windows are below us. Exit early.
3089 }
chaviw98318de2021-05-19 16:45:23 -05003090 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003091 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3092 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003093 if (DEBUG_TOUCH_OCCLUSION) {
3094 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003095 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003096 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003097 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3098 // we perform the checks below to see if the touch can be propagated or not based on the
3099 // window's touch occlusion mode
3100 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3101 info.hasBlockingOcclusion = true;
3102 info.obscuringUid = otherInfo->ownerUid;
3103 info.obscuringPackage = otherInfo->packageName;
3104 break;
3105 }
3106 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003107 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003108 float opacity =
3109 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3110 // Given windows A and B:
3111 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3112 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3113 opacityByUid[uid] = opacity;
3114 if (opacity > info.obscuringOpacity) {
3115 info.obscuringOpacity = opacity;
3116 info.obscuringUid = uid;
3117 info.obscuringPackage = otherInfo->packageName;
3118 }
3119 }
3120 }
3121 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003122 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003123 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003124 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003125 return info;
3126}
3127
chaviw98318de2021-05-19 16:45:23 -05003128std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003129 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003130 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003131 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3132 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3133 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003134 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003135 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003136 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3137 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003138 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3139 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3140 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003141 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003142}
3143
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003144bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3145 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003146 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3147 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003148 return false;
3149 }
3150 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003151 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003152 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003153 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003154 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3155 return false;
3156 }
3157 return true;
3158}
3159
chaviw98318de2021-05-19 16:45:23 -05003160bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003163 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3164 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003165 if (windowHandle == otherHandle) {
3166 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
chaviw98318de2021-05-19 16:45:23 -05003168 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003169 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003170 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 return true;
3172 }
3173 }
3174 return false;
3175}
3176
chaviw98318de2021-05-19 16:45:23 -05003177bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003178 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003179 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3180 const WindowInfo* windowInfo = windowHandle->getInfo();
3181 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003182 if (windowHandle == otherHandle) {
3183 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003184 }
chaviw98318de2021-05-19 16:45:23 -05003185 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003186 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003187 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003188 return true;
3189 }
3190 }
3191 return false;
3192}
3193
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003194std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003195 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003196 if (applicationHandle != nullptr) {
3197 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003198 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 } else {
3200 return applicationHandle->getName();
3201 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003202 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003203 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003205 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
3207}
3208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003209void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003210 if (!isUserActivityEvent(eventEntry)) {
3211 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003212 return;
3213 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003214
3215 const int32_t eventType = getUserActivityEventType(eventEntry);
3216 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3217 // Note that we're directly getting the time diff between the current event and the previous
3218 // event. This is assuming that the first user event always happens at a timestamp that is
3219 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3220 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3221 // value than the potential first user activity event time, so this is ok.
3222 std::chrono::nanoseconds timeSinceLastEvent =
3223 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3224 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3225 return;
3226 }
3227 }
3228
Tiger Huang721e26f2018-07-24 22:26:19 +08003229 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003230 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003231 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003233 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003234 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003235 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237 }
3238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003239 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003240 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003241 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3242 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 return;
3244 }
Josep del Riob3981622023-04-18 15:49:45 +00003245 if (windowDisablingUserActivityInfo != nullptr) {
3246 if (DEBUG_DISPATCH_CYCLE) {
3247 ALOGD("Not poking user activity: disabled by window '%s'.",
3248 windowDisablingUserActivityInfo->name.c_str());
3249 }
3250 return;
3251 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003254 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003255 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3256 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 return;
3258 }
Josep del Riob3981622023-04-18 15:49:45 +00003259 // If the key code is unknown, we don't consider it user activity
3260 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3261 return;
3262 }
3263 // Don't inhibit events that were intercepted or are not passed to
3264 // the apps, like system shortcuts
3265 if (windowDisablingUserActivityInfo != nullptr &&
3266 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3267 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3268 if (DEBUG_DISPATCH_CYCLE) {
3269 ALOGD("Not poking user activity: disabled by window '%s'.",
3270 windowDisablingUserActivityInfo->name.c_str());
3271 }
3272 return;
3273 }
3274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003275 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003277 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003278 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003279 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003280 break;
3281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003284 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003285 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3286 REQUIRES(mLock) {
3287 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003288 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003289 };
3290 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291}
3292
3293void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003294 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003295 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003296 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003297 ATRACE_NAME_IF(ATRACE_ENABLED(),
3298 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3299 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003300 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003301 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003302 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003303 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003304 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003305 inputTarget.getPointerInfoString().c_str());
3306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
3308 // Skip this event if the connection status is not normal.
3309 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003310 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003311 if (DEBUG_DISPATCH_CYCLE) {
3312 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003313 connection->getInputChannelName().c_str(),
3314 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 return;
3317 }
3318
3319 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003320 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003321 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003323 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003325 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003326 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003327 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3328 logDispatchStateLocked();
3329 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3330 "target on connection "
3331 << connection->getInputChannelName() << " for "
3332 << originalMotionEntry.getDescription();
3333 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003335 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003336 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 if (!splitMotionEntry) {
3338 return; // split event was dropped
3339 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003340 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3341 std::string reason = std::string("reason=pointer cancel on split window");
3342 android_log_event_list(LOGTAG_INPUT_CANCEL)
3343 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3344 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003345 if (DEBUG_FOCUS) {
3346 ALOGD("channel '%s' ~ Split motion event.",
3347 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003348 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003349 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003350 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3351 std::move(splitMotionEntry),
3352 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 return;
3354 }
3355 }
3356
3357 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003358 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3359 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360}
3361
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003362void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3363 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3364 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003365 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003366 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3367 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003368 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003369
hongzuo liu95785e22022-09-06 02:51:35 +00003370 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003372 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
3374 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003375 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 startDispatchCycleLocked(currentTime, connection);
3377 }
3378}
3379
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003380void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003381 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003382 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003383 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3384 eventEntry->type == EventEntry::Type::MOTION;
3385 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3386 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3387 << inputTarget << " connection: " << connection->getInputChannelName()
3388 << " entry: " << eventEntry->getDescription();
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 // This is a new event.
3391 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003392 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003393 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
Prabir Pradhana67623c2024-02-21 06:57:36 +00003394 mWindowInfosVsyncId, mTracer.get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003396 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3397 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003398 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003400 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003401 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3403 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003404 LOG(WARNING) << "channel " << connection->getInputChannelName()
3405 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 return; // skip the inconsistent event
3407 }
3408 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003412 std::shared_ptr<const MotionEntry> resolvedMotion =
3413 std::static_pointer_cast<const MotionEntry>(eventEntry);
3414 {
3415 // Determine the resolved motion entry.
3416 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3417 int32_t resolvedAction = motionEntry.action;
3418 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003420 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003421 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003422 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003423 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003424 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003425 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003426 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003427 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003428 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003429 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3430 }
3431 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3432 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3433 motionEntry.displayId)) {
3434 if (DEBUG_DISPATCH_CYCLE) {
3435 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3436 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3437 "enter event";
3438 }
3439 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3440 }
3441
3442 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3443 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3444 }
3445 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3446 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3447 }
3448 if (dispatchEntry->targetFlags.test(
3449 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3450 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3451 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003452 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3453 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3454 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003455
3456 dispatchEntry->resolvedFlags = resolvedFlags;
3457 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003458 std::optional<std::vector<PointerProperties>> usingProperties;
3459 std::optional<std::vector<PointerCoords>> usingCoords;
3460 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3461 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3462 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3463 // the dispatcher, and therefore the coordinates of this event are currently
3464 // incorrect. These events should use the coordinates of the last dispatched
3465 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3466 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3467 std::optional<std::pair<std::vector<PointerProperties>,
3468 std::vector<PointerCoords>>>
3469 pointerInfo =
3470 connection->inputState.getPointersOfLastEvent(motionEntry,
3471 hovering);
3472 if (pointerInfo) {
3473 usingProperties = pointerInfo->first;
3474 usingCoords = pointerInfo->second;
3475 }
3476 }
Prabir Pradhana67623c2024-02-21 06:57:36 +00003477 {
3478 // Generate a new MotionEntry with a new eventId using the resolved action
3479 // and flags, and set it as the resolved entry.
3480 auto newEntry = std::make_shared<
3481 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3482 motionEntry.eventTime, motionEntry.deviceId,
3483 motionEntry.source, motionEntry.displayId,
3484 motionEntry.policyFlags, resolvedAction,
3485 motionEntry.actionButton, resolvedFlags,
3486 motionEntry.metaState, motionEntry.buttonState,
3487 motionEntry.classification, motionEntry.edgeFlags,
3488 motionEntry.xPrecision, motionEntry.yPrecision,
3489 motionEntry.xCursorPosition,
3490 motionEntry.yCursorPosition, motionEntry.downTime,
3491 usingProperties.value_or(
3492 motionEntry.pointerProperties),
3493 usingCoords.value_or(motionEntry.pointerCoords));
3494 if (mTracer) {
3495 ensureEventTraced(motionEntry);
3496 newEntry->traceTracker =
3497 mTracer->traceDerivedEvent(*newEntry,
3498 *motionEntry.traceTracker);
3499 }
3500 resolvedMotion = newEntry;
3501 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003502 if (ATRACE_ENABLED()) {
3503 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3504 ") to MotionEvent(id=0x%" PRIx32 ").",
3505 motionEntry.id, resolvedMotion->id);
3506 ATRACE_NAME(message.c_str());
3507 }
3508
3509 // Set the resolved motion entry in the DispatchEntry.
3510 dispatchEntry->eventEntry = resolvedMotion;
3511 eventEntry = resolvedMotion;
3512 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003515 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3516 // devices being active at the same time in the same window, so if a new device is
3517 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003518 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003519 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003520 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003521 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003522 << connection->getInputChannelName() << " with event "
3523 << cancelEvent->getDescription();
3524 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003525 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhana67623c2024-02-21 06:57:36 +00003526 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId,
3527 mTracer.get());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003528
3529 // Send these cancel events to the queue before sending the event from the new
3530 // device.
3531 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3532 }
3533
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003534 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003535 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003536 LOG(WARNING) << "channel " << connection->getInputChannelName()
3537 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003538 return; // skip the inconsistent event
3539 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003540 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003541 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003542 // Skip reporting pointer down outside focus to the policy.
3543 break;
3544 }
3545
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003546 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003547 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003548
3549 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003551 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003552 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003553 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3554 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003555 break;
3556 }
Chris Yef59a2f42020-10-16 12:55:26 -07003557 case EventEntry::Type::SENSOR: {
3558 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3559 break;
3560 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003561 case EventEntry::Type::CONFIGURATION_CHANGED:
3562 case EventEntry::Type::DEVICE_RESET: {
3563 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003564 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003565 break;
3566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 }
3568
3569 // Remember that we are waiting for this dispatch to complete.
3570 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003571 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573
3574 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003575 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003576 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003577}
3578
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003579/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003580 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003582 * The first role is to log input interaction with windows, which helps determine what the user was
3583 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3584 * that user started interacting with launcher window, as well as any other window that received
3585 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3586 * when the set of tokens that received the event changes. It is not logged again as long as the
3587 * user is interacting with the same windows.
3588 *
3589 * The second role is to track input device activity for metrics collection. For each input event,
3590 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3591 * input_interaction logs, the device interaction is reported even when the set of interaction
3592 * tokens do not change.
3593 *
3594 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3595 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003596 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003597void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3598 const std::vector<InputTarget>& targets) {
3599 int32_t deviceId;
3600 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003601 // Skip ACTION_UP events, and all events other than keys and motions
3602 if (entry.type == EventEntry::Type::KEY) {
3603 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3604 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3605 return;
3606 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003607 deviceId = keyEntry.deviceId;
3608 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003609 } else if (entry.type == EventEntry::Type::MOTION) {
3610 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3611 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003612 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3613 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003614 return;
3615 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003616 deviceId = motionEntry.deviceId;
3617 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003618 } else {
3619 return; // Not a key or a motion
3620 }
3621
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003622 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003623 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003624 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003625 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003626 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003627 continue; // Skip windows that receive ACTION_OUTSIDE
3628 }
3629
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003630 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003631 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003632 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003633 if (target.windowHandle) {
3634 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3635 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003636 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003637
3638 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3639 REQUIRES(mLock) {
3640 scoped_unlock unlock(mLock);
3641 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3642 };
3643 postCommandLocked(std::move(command));
3644
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003645 if (newConnectionTokens == mInteractionConnectionTokens) {
3646 return; // no change
3647 }
3648 mInteractionConnectionTokens = newConnectionTokens;
3649
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003650 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003651 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003652 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003653 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003654 std::string message = "Interaction with: " + targetList;
3655 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003656 message += "<none>";
3657 }
3658 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3659}
3660
chaviwfd6d3512019-03-25 13:23:49 -07003661void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003662 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003663 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003664 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3665 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003666 return;
3667 }
3668
Vishnu Nairc519ff72021-01-21 08:23:08 -08003669 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003670 if (focusedToken == token) {
3671 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003672 return;
3673 }
3674
Prabir Pradhancef936d2021-07-21 16:17:52 +00003675 auto command = [this, token]() REQUIRES(mLock) {
3676 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003677 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003678 };
3679 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680}
3681
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003682status_t InputDispatcher::publishMotionEvent(Connection& connection,
3683 DispatchEntry& dispatchEntry) const {
3684 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3685 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3686
3687 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003688 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003689
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003690 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003691 // Set the X and Y offset and X and Y scale depending on the input source.
3692 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003693 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003694 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3695 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003696 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003697 scaledCoords[i] = motionEntry.pointerCoords[i];
3698 // Don't apply window scale here since we don't want scale to affect raw
3699 // coordinates. The scale will be sent back to the client and applied
3700 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003701 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003702 }
3703 usingCoords = scaledCoords;
3704 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003705 }
3706
3707 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3708
3709 // Publish the motion event.
3710 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003711 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3712 motionEntry.source, motionEntry.displayId, std::move(hmac),
3713 motionEntry.action, motionEntry.actionButton,
3714 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3715 motionEntry.metaState, motionEntry.buttonState,
3716 motionEntry.classification, dispatchEntry.transform,
3717 motionEntry.xPrecision, motionEntry.yPrecision,
3718 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3719 dispatchEntry.rawTransform, motionEntry.downTime,
3720 motionEntry.eventTime, motionEntry.getPointerCount(),
3721 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003722}
3723
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003725 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003726 ATRACE_NAME_IF(ATRACE_ENABLED(),
3727 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3728 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003729 if (DEBUG_DISPATCH_CYCLE) {
3730 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003733 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003734 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003736 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003737 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
3739 // Publish the event.
3740 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3742 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003743 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3745 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003746 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003747 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3748 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003751 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003752 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003753 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3754 keyEntry.deviceId, keyEntry.source,
3755 keyEntry.displayId, std::move(hmac),
3756 keyEntry.action, dispatchEntry->resolvedFlags,
3757 keyEntry.keyCode, keyEntry.scanCode,
3758 keyEntry.metaState, keyEntry.repeatCount,
3759 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003760 if (mTracer) {
3761 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3762 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003766 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003767 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003768 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3769 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003770 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003771 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003772 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003773 if (mTracer) {
3774 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3775 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 break;
3777 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003778
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003780 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003781 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003782 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003783 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003784 break;
3785 }
3786
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003787 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3788 const TouchModeEntry& touchModeEntry =
3789 static_cast<const TouchModeEntry&>(eventEntry);
3790 status = connection->inputPublisher
3791 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3792 touchModeEntry.inTouchMode);
3793
3794 break;
3795 }
3796
Prabir Pradhan99987712020-11-10 18:43:05 -08003797 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3798 const auto& captureEntry =
3799 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3800 status = connection->inputPublisher
3801 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003802 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003803 break;
3804 }
3805
arthurhungb89ccb02020-12-30 16:19:01 +08003806 case EventEntry::Type::DRAG: {
3807 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3808 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3809 dragEntry.id, dragEntry.x,
3810 dragEntry.y,
3811 dragEntry.isExiting);
3812 break;
3813 }
3814
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003815 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003816 case EventEntry::Type::DEVICE_RESET:
3817 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003818 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003819 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823
3824 // Check the result.
3825 if (status) {
3826 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003827 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 "This is unexpected because the wait queue is empty, so the pipe "
3830 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003831 "event to it, status=%s(%d)",
3832 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3833 status);
Harry Cutts33476232023-01-30 19:57:29 +00003834 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 } else {
3836 // Pipe is full and we are waiting for the app to finish process some events
3837 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003838 if (DEBUG_DISPATCH_CYCLE) {
3839 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3840 "waiting for the application to catch up",
3841 connection->getInputChannelName().c_str());
3842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 }
3844 } else {
3845 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003846 "status=%s(%d)",
3847 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3848 status);
Harry Cutts33476232023-01-30 19:57:29 +00003849 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851 return;
3852 }
3853
3854 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003855 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3856 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3857 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003858 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003859 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003860 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003861 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003862 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
3864}
3865
chaviw09c8d2d2020-08-24 15:48:26 -07003866std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3867 size_t size;
3868 switch (event.type) {
3869 case VerifiedInputEvent::Type::KEY: {
3870 size = sizeof(VerifiedKeyEvent);
3871 break;
3872 }
3873 case VerifiedInputEvent::Type::MOTION: {
3874 size = sizeof(VerifiedMotionEvent);
3875 break;
3876 }
3877 }
3878 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3879 return mHmacKeyManager.sign(start, size);
3880}
3881
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003882const std::array<uint8_t, 32> InputDispatcher::getSignature(
3883 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003884 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003885 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003886 // Only sign events up and down events as the purely move events
3887 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003888 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003889 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003890
3891 VerifiedMotionEvent verifiedEvent =
3892 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3893 verifiedEvent.actionMasked = actionMasked;
3894 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3895 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003896}
3897
3898const std::array<uint8_t, 32> InputDispatcher::getSignature(
3899 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3900 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3901 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003902 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003903}
3904
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003906 const std::shared_ptr<Connection>& connection,
3907 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003908 if (DEBUG_DISPATCH_CYCLE) {
3909 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3910 connection->getInputChannelName().c_str(), seq, toString(handled));
3911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003913 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 return;
3915 }
3916
3917 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003918 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3919 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3920 };
3921 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922}
3923
3924void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003925 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003926 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003927 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003928 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3929 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
3932 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003933 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003934 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003935 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003936 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
3938 // The connection appears to be unrecoverably broken.
3939 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003940 if (connection->status == Connection::Status::NORMAL) {
3941 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
3943 if (notify) {
3944 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003945 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3946 connection->getInputChannelName().c_str());
3947
3948 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003949 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003950 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003951 };
3952 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 }
3954 }
3955}
3956
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003957void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003958 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003959 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003960 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 }
3962}
3963
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003964void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003966 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968}
3969
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003970int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3971 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003972 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003973 if (connection == nullptr) {
3974 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3975 connectionToken.get(), events);
3976 return 0; // remove the callback
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003979 bool notify;
3980 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3981 if (!(events & ALOOPER_EVENT_INPUT)) {
3982 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3983 "events=0x%x",
3984 connection->getInputChannelName().c_str(), events);
3985 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003988 nsecs_t currentTime = now();
3989 bool gotOne = false;
3990 status_t status = OK;
3991 for (;;) {
3992 Result<InputPublisher::ConsumerResponse> result =
3993 connection->inputPublisher.receiveConsumerResponse();
3994 if (!result.ok()) {
3995 status = result.error().code();
3996 break;
3997 }
3998
3999 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
4000 const InputPublisher::Finished& finish =
4001 std::get<InputPublisher::Finished>(*result);
4002 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
4003 finish.consumeTime);
4004 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004005 if (shouldReportMetricsForConnection(*connection)) {
4006 const InputPublisher::Timeline& timeline =
4007 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004008 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
4009 connection->getToken(),
4010 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004011 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004012 }
4013 gotOne = true;
4014 }
4015 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004016 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004017 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 return 1;
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 }
4021
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004022 notify = status != DEAD_OBJECT || !connection->monitor;
4023 if (notify) {
4024 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4025 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4026 status);
4027 }
4028 } else {
4029 // Monitor channels are never explicitly unregistered.
4030 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004031 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004032 notify = !connection->monitor && stillHaveWindowHandle;
4033 if (notify) {
4034 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4035 connection->getInputChannelName().c_str(), events);
4036 }
4037 }
4038
4039 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004040 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004041 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042}
4043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004044void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004046 // Cancel windows (i.e. non-monitors).
4047 // A channel must have at least one window to receive any input. If a window was removed, the
4048 // event streams directed to the window will already have been canceled during window removal.
4049 // So there is no need to generate cancellations for connections without any windows.
4050 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4051 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4052 // through a non-touched window if there are more than one window for an input channel.
4053 if (cancelPointers) {
4054 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4055 if (options.displayId.has_value() && options.displayId != displayId) {
4056 continue;
4057 }
4058 for (const auto& touchedWindow : touchState.windows) {
4059 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4060 }
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004063 // Follow up by generating cancellations for all windows, because we don't explicitly track
4064 // the windows that have an ongoing focus event stream.
4065 if (cancelNonPointers) {
4066 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4067 for (const auto& windowHandle : handles) {
4068 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4069 }
4070 }
4071 }
4072
4073 // Cancel monitors.
4074 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075}
4076
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004078 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004079 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004080 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004081 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4082 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004083 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004084 }
4085}
4086
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004087void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4088 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4089 const std::shared_ptr<Connection>& connection) {
4090 if (windowHandle == nullptr) {
4091 LOG(FATAL) << __func__ << ": Window handle must not be null";
4092 }
4093 if (connection) {
4094 // The connection can be optionally provided to avoid multiple lookups.
4095 if (windowHandle->getToken() != connection->getToken()) {
4096 LOG(FATAL) << __func__
4097 << ": Wrong connection provided for window: " << windowHandle->getName();
4098 }
4099 }
4100
4101 std::shared_ptr<Connection> resolvedConnection =
4102 connection ? connection : getConnectionLocked(windowHandle->getToken());
4103 if (!resolvedConnection) {
4104 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4105 return;
4106 }
4107 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4108}
4109
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004111 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4112 const sp<WindowInfoHandle>& window) {
4113 if (!connection->monitor && window == nullptr) {
4114 LOG(FATAL) << __func__
4115 << ": Cannot send event to non-monitor channel without a window - channel: "
4116 << connection->getInputChannelName();
4117 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004118 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 return;
4120 }
4121
4122 nsecs_t currentTime = now();
4123
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004124 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004125 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004127 if (cancelationEvents.empty()) {
4128 return;
4129 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004130
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004131 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4132 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004133 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004134 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004135 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004137
Arthur Hungb3307ee2021-10-14 10:57:37 +00004138 std::string reason = std::string("reason=").append(options.reason);
4139 android_log_event_list(LOGTAG_INPUT_CANCEL)
4140 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4141
hongzuo liu95785e22022-09-06 02:51:35 +00004142 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004143 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004144 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004145 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004146
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004147 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004148 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004149 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004150
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004151 switch (cancelationEventEntry->type) {
4152 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004153 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004154 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004155 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4156 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004157 } else {
4158 targets.emplace_back(fallbackTarget);
4159 }
4160 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004163 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004164 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004165 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004166 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004167 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004168 pointerIndex++) {
4169 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4170 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004171 if (mDragState && mDragState->dragWindow->getToken() == token &&
4172 pointerIds.test(mDragState->pointerId)) {
4173 LOG(INFO) << __func__
4174 << ": Canceling drag and drop because the pointers for the drag "
4175 "window are being canceled.";
4176 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4177 mDragState.reset();
4178 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004179 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4180 ftl::Flags<InputTarget::Flags>(), pointerIds,
4181 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004182 } else {
4183 targets.emplace_back(fallbackTarget);
4184 const auto it = mDisplayInfos.find(motionEntry.displayId);
4185 if (it != mDisplayInfos.end()) {
4186 targets.back().displayTransform = it->second.transform;
4187 targets.back().setDefaultPointerTransform(it->second.transform);
4188 }
4189 }
4190 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004191 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004193 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004194 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004195 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4196 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004197 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004198 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004199 break;
4200 }
4201 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004202 case EventEntry::Type::DEVICE_RESET:
4203 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004204 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004205 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004206 break;
4207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004210 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004211 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004213
hongzuo liu95785e22022-09-06 02:51:35 +00004214 // If the outbound queue was previously empty, start the dispatch cycle going.
4215 if (wasEmpty && !connection->outboundQueue.empty()) {
4216 startDispatchCycleLocked(currentTime, connection);
4217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218}
4219
Svet Ganov5d3bc372020-01-26 23:11:07 -08004220void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004221 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004222 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004223 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004224 return;
4225 }
4226
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004227 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004228 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004229
4230 if (downEvents.empty()) {
4231 return;
4232 }
4233
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004234 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004235 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4236 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004237 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004239 const auto [_, touchedWindowState, displayId] =
4240 findTouchStateWindowAndDisplayLocked(connection->getToken());
4241 if (touchedWindowState == nullptr) {
4242 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4243 }
4244 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004245
hongzuo liu95785e22022-09-06 02:51:35 +00004246 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004248 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004249 switch (downEventEntry->type) {
4250 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004251 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4252 if (windowHandle != nullptr) {
4253 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004254 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004255 pointerIndex++) {
4256 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4257 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004258 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4259 targetFlags, pointerIds, motionEntry.downTime,
4260 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004261 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004262 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004263 const auto it = mDisplayInfos.find(motionEntry.displayId);
4264 if (it != mDisplayInfos.end()) {
4265 targets.back().displayTransform = it->second.transform;
4266 targets.back().setDefaultPointerTransform(it->second.transform);
4267 }
4268 }
4269 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004270 break;
4271 }
4272
4273 case EventEntry::Type::KEY:
4274 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004275 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004276 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004277 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004278 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004279 case EventEntry::Type::SENSOR:
4280 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004281 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004282 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004283 break;
4284 }
4285 }
4286
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004287 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004288 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004289 }
4290
hongzuo liu95785e22022-09-06 02:51:35 +00004291 // If the outbound queue was previously empty, start the dispatch cycle going.
4292 if (wasEmpty && !connection->outboundQueue.empty()) {
4293 startDispatchCycleLocked(downTime, connection);
4294 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004295}
4296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004297std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004298 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4299 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004300 const auto& [action, pointerProperties, pointerCoords] =
4301 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4302 /*historySize=*/0, originalMotionEntry.pointerProperties,
4303 originalMotionEntry.pointerCoords, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004305 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4306 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004307 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4308 logDispatchStateLocked();
4309 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4310 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4311 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004312 }
4313
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004314 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004315 ATRACE_NAME_IF(ATRACE_ENABLED(),
4316 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4317 ").",
4318 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004320 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4321 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004322 originalMotionEntry.deviceId, originalMotionEntry.source,
4323 originalMotionEntry.displayId,
4324 originalMotionEntry.policyFlags, action,
4325 originalMotionEntry.actionButton,
4326 originalMotionEntry.flags, originalMotionEntry.metaState,
4327 originalMotionEntry.buttonState,
4328 originalMotionEntry.classification,
4329 originalMotionEntry.edgeFlags,
4330 originalMotionEntry.xPrecision,
4331 originalMotionEntry.yPrecision,
4332 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004333 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004334 pointerProperties, pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +00004335 if (mTracer) {
4336 splitMotionEntry->traceTracker =
4337 mTracer->traceDerivedEvent(*splitMotionEntry, *originalMotionEntry.traceTracker);
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 return splitMotionEntry;
4341}
4342
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004343void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4344 std::scoped_lock _l(mLock);
4345 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4346}
4347
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004348void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004349 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004350 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
Antonio Kantekf16f2832021-09-28 04:39:20 +00004353 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004355 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004357 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004358 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 } // release lock
4361
4362 if (needWake) {
4363 mLooper->wake();
4364 }
4365}
4366
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004368 ALOGD_IF(debugInboundEventDetails(),
4369 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4370 ", deviceId=%d, source=%s, displayId=%" PRId32
4371 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4372 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4374 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4375 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004376 Result<void> keyCheck = validateKeyEvent(args.action);
4377 if (!keyCheck.ok()) {
4378 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 return;
4380 }
4381
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004382 uint32_t policyFlags = args.policyFlags;
4383 int32_t flags = args.flags;
4384 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004385 // InputDispatcher tracks and generates key repeats on behalf of
4386 // whatever notifies it, so repeatCount should always be set to 0
4387 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4389 policyFlags |= POLICY_FLAG_VIRTUAL;
4390 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 if (policyFlags & POLICY_FLAG_FUNCTION) {
4393 metaState |= AMETA_FUNCTION_ON;
4394 }
4395
4396 policyFlags |= POLICY_FLAG_TRUSTED;
4397
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004398 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4401 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4402 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Michael Wright2b3c3302018-03-02 17:19:13 +00004404 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004405 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004406 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4407 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410
Antonio Kantekf16f2832021-09-28 04:39:20 +00004411 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 { // acquire lock
4413 mLock.lock();
4414
4415 if (shouldSendKeyToInputFilterLocked(args)) {
4416 mLock.unlock();
4417
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004418 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004419 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 return; // event was consumed by the filter
4421 }
4422
4423 mLock.lock();
4424 }
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004427 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4428 args.deviceId, args.source, args.displayId, policyFlags,
4429 args.action, flags, keyCode, args.scanCode, metaState,
4430 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004431 if (mTracer) {
4432 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004435 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 mLock.unlock();
4437 } // release lock
4438
4439 if (needWake) {
4440 mLooper->wake();
4441 }
4442}
4443
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004444bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 return mInputFilterEnabled;
4446}
4447
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004448void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004449 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004450 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004451 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004452 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004453 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4454 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004455 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4456 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4457 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4458 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4459 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004460 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004461 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4462 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004463 i, args.pointerProperties[i].id,
4464 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4465 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4466 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4467 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4468 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4469 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4470 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4471 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4472 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4473 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004476
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004477 Result<void> motionCheck =
4478 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4479 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004480 if (!motionCheck.ok()) {
4481 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4482 return;
4483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004485 if (DEBUG_VERIFY_EVENTS) {
4486 auto [it, _] =
4487 mVerifiersByDisplay.try_emplace(args.displayId,
4488 StringPrintf("display %" PRId32, args.displayId));
4489 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004490 it->second.processMovement(args.deviceId, args.source, args.action,
4491 args.getPointerCount(), args.pointerProperties.data(),
4492 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004493 if (!result.ok()) {
4494 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4495 }
4496 }
4497
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004498 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004500
4501 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004502 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4503 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004504 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4505 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004506 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Antonio Kantekf16f2832021-09-28 04:39:20 +00004509 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 { // acquire lock
4511 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004512 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4513 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4514 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004515 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004516 if (touchStateIt != mTouchStatesByDisplay.end()) {
4517 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004518 if (touchState.hasTouchingPointers(args.deviceId) ||
4519 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004520 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4521 }
4522 }
4523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
4525 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004526 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004528 displayTransform = it->second.transform;
4529 }
4530
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 mLock.unlock();
4532
4533 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004534 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4535 args.action, args.actionButton, args.flags, args.edgeFlags,
4536 args.metaState, args.buttonState, args.classification,
4537 displayTransform, args.xPrecision, args.yPrecision,
4538 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004539 args.downTime, args.eventTime, args.getPointerCount(),
4540 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541
4542 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004543 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 return; // event was consumed by the filter
4545 }
4546
4547 mLock.lock();
4548 }
4549
4550 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004551 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004552 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4553 args.deviceId, args.source, args.displayId,
4554 policyFlags, args.action, args.actionButton,
4555 args.flags, args.metaState, args.buttonState,
4556 args.classification, args.edgeFlags, args.xPrecision,
4557 args.yPrecision, args.xCursorPosition,
4558 args.yCursorPosition, args.downTime,
4559 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004560 if (mTracer) {
4561 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004564 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4565 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004566 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004567 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004568 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4569 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4570 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004571 }
4572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004573 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 mLock.unlock();
4575 } // release lock
4576
4577 if (needWake) {
4578 mLooper->wake();
4579 }
4580}
4581
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004582void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004583 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004584 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4585 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004586 args.id, args.eventTime, args.deviceId, args.source,
4587 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004588 }
Chris Yef59a2f42020-10-16 12:55:26 -07004589
Antonio Kantekf16f2832021-09-28 04:39:20 +00004590 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004591 { // acquire lock
4592 mLock.lock();
4593
4594 // Just enqueue a new sensor event.
4595 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004596 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4597 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4598 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004599
4600 needWake = enqueueInboundEventLocked(std::move(newEntry));
4601 mLock.unlock();
4602 } // release lock
4603
4604 if (needWake) {
4605 mLooper->wake();
4606 }
4607}
4608
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004609void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004610 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4612 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004613 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004614 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004615}
4616
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004617bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004618 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004621void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004622 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004623 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4624 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004625 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004628 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004630 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631}
4632
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004633void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004634 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4636 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638
Antonio Kantekf16f2832021-09-28 04:39:20 +00004639 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004641 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004643 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004644 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004645 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004646
4647 for (auto& [_, verifier] : mVerifiersByDisplay) {
4648 verifier.resetDevice(args.deviceId);
4649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 } // release lock
4651
4652 if (needWake) {
4653 mLooper->wake();
4654 }
4655}
4656
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004657void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004658 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004659 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4660 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004661 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004662
Antonio Kantekf16f2832021-09-28 04:39:20 +00004663 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004664 { // acquire lock
4665 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004666 auto entry =
4667 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004668 needWake = enqueueInboundEventLocked(std::move(entry));
4669 } // release lock
4670
4671 if (needWake) {
4672 mLooper->wake();
4673 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004674}
4675
Prabir Pradhan5735a322022-04-11 17:23:34 +00004676InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004677 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004678 InputEventInjectionSync syncMode,
4679 std::chrono::milliseconds timeout,
4680 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004681 Result<void> eventValidation = validateInputEvent(*event);
4682 if (!eventValidation.ok()) {
4683 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4684 return InputEventInjectionResult::FAILED;
4685 }
4686
Prabir Pradhan65613802023-02-22 23:36:58 +00004687 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004688 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4689 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4690 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4691 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004692 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004693 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694
Prabir Pradhan5735a322022-04-11 17:23:34 +00004695 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004697 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004698 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4699 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4700 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4701 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4702 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004703 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004704 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004705 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004706 }
4707
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004708 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4709 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4710
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004711 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004713 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004714 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004715 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004716 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004717 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4718 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4719 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004720 int32_t keyCode = incomingKey.getKeyCode();
4721 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004722 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004723 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004724 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4725 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4726 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4729 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004730 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004731
4732 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4733 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004734 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4736 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4737 std::to_string(t.duration().count()).c_str());
4738 }
4739 }
4740
4741 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004742 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004743 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4744 incomingKey.getEventTime(), resolvedDeviceId,
4745 incomingKey.getSource(), incomingKey.getDisplayId(),
4746 policyFlags, action, flags, keyCode,
4747 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004748 incomingKey.getRepeatCount(),
4749 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004750 if (mTracer) {
4751 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4752 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004753 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004757 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004758 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004759 const bool isPointerEvent =
4760 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4761 // If a pointer event has no displayId specified, inject it to the default display.
4762 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4763 ? ADISPLAY_ID_DEFAULT
4764 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004765 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004766
4767 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004768 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004770 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4771 motionEvent.getAction(), eventTime,
4772 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4774 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4775 std::to_string(t.duration().count()).c_str());
4776 }
4777 }
4778
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004779 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4780 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4781 }
4782
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004783 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004784 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004785 const size_t pointerCount = motionEvent.getPointerCount();
4786 const std::vector<PointerProperties>
4787 pointerProperties(motionEvent.getPointerProperties(),
4788 motionEvent.getPointerProperties() + pointerCount);
4789
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004790 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004791 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004792 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4793 *sampleEventTimes, resolvedDeviceId,
4794 motionEvent.getSource(), displayId, policyFlags,
4795 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004796 motionEvent.getActionButton(), flags,
4797 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004798 motionEvent.getButtonState(),
4799 motionEvent.getClassification(),
4800 motionEvent.getEdgeFlags(),
4801 motionEvent.getXPrecision(),
4802 motionEvent.getYPrecision(),
4803 motionEvent.getRawXCursorPosition(),
4804 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004805 motionEvent.getDownTime(), pointerProperties,
4806 std::vector<PointerCoords>(samplePointerCoords,
4807 samplePointerCoords +
4808 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004809 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004810 if (mTracer) {
4811 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4812 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004813 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004814 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004815 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004816 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004817 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004818 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4819 resolvedDeviceId, motionEvent.getSource(), displayId,
4820 policyFlags, motionEvent.getAction(),
4821 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004822 motionEvent.getMetaState(), motionEvent.getButtonState(),
4823 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4824 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4825 motionEvent.getRawXCursorPosition(),
4826 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4827 pointerProperties,
4828 std::vector<PointerCoords>(samplePointerCoords,
4829 samplePointerCoords +
4830 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004831 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4832 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004833 if (mTracer) {
4834 nextInjectedEntry->traceTracker =
4835 mTracer->traceInboundEvent(*nextInjectedEntry);
4836 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004837 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004838 }
4839 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004843 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004848 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004849 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004850 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004851 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004852 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004853 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
4855
4856 mLock.unlock();
4857
4858 if (needWake) {
4859 mLooper->wake();
4860 }
4861
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004864 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 if (syncMode == InputEventInjectionSync::NONE) {
4867 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 } else {
4869 for (;;) {
4870 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004871 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 break;
4873 }
4874
4875 nsecs_t remainingTimeout = endTime - now();
4876 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004877 if (DEBUG_INJECTION) {
4878 ALOGD("injectInputEvent - Timed out waiting for injection result "
4879 "to become available.");
4880 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004881 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 break;
4883 }
4884
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004885 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 }
4887
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004888 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4889 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004891 if (DEBUG_INJECTION) {
4892 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4893 injectionState->pendingForegroundDispatches);
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 nsecs_t remainingTimeout = endTime - now();
4896 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004897 if (DEBUG_INJECTION) {
4898 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4899 "dispatches to finish.");
4900 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 break;
4903 }
4904
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004905 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 }
4907 }
4908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 } // release lock
4910
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004911 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004912 LOG(INFO) << "injectInputEvent - Finished with result "
4913 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 return injectionResult;
4917}
4918
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004919std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004920 std::array<uint8_t, 32> calculatedHmac;
4921 std::unique_ptr<VerifiedInputEvent> result;
4922 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004923 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004924 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4925 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4926 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004927 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004928 break;
4929 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004930 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004931 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4932 VerifiedMotionEvent verifiedMotionEvent =
4933 verifiedMotionEventFromMotionEvent(motionEvent);
4934 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004935 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004936 break;
4937 }
4938 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004939 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004940 return nullptr;
4941 }
4942 }
4943 if (calculatedHmac == INVALID_HMAC) {
4944 return nullptr;
4945 }
tyiu1573a672023-02-21 22:38:32 +00004946 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004947 return nullptr;
4948 }
4949 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004950}
4951
Prabir Pradhan24047542023-11-02 17:14:59 +00004952void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004953 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004954 if (!entry.injectionState) {
4955 // Not an injected event.
4956 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004958
4959 InjectionState& injectionState = *entry.injectionState;
4960 if (DEBUG_INJECTION) {
4961 LOG(INFO) << "Setting input event injection result to "
4962 << ftl::enum_string(injectionResult);
4963 }
4964
4965 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4966 // Log the outcome since the injector did not wait for the injection result.
4967 switch (injectionResult) {
4968 case InputEventInjectionResult::SUCCEEDED:
4969 ALOGV("Asynchronous input event injection succeeded.");
4970 break;
4971 case InputEventInjectionResult::TARGET_MISMATCH:
4972 ALOGV("Asynchronous input event injection target mismatch.");
4973 break;
4974 case InputEventInjectionResult::FAILED:
4975 ALOGW("Asynchronous input event injection failed.");
4976 break;
4977 case InputEventInjectionResult::TIMED_OUT:
4978 ALOGW("Asynchronous input event injection timed out.");
4979 break;
4980 case InputEventInjectionResult::PENDING:
4981 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4982 break;
4983 }
4984 }
4985
4986 injectionState.injectionResult = injectionResult;
4987 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988}
4989
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004990void InputDispatcher::transformMotionEntryForInjectionLocked(
4991 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004992 // Input injection works in the logical display coordinate space, but the input pipeline works
4993 // display space, so we need to transform the injected events accordingly.
4994 const auto it = mDisplayInfos.find(entry.displayId);
4995 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004996 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004997
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004998 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4999 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5000 const vec2 cursor =
5001 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5002 {entry.xCursorPosition, entry.yCursorPosition});
5003 entry.xCursorPosition = cursor.x;
5004 entry.yCursorPosition = cursor.y;
5005 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005006 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005007 entry.pointerCoords[i] =
5008 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5009 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005010 }
5011}
5012
Prabir Pradhan24047542023-11-02 17:14:59 +00005013void InputDispatcher::incrementPendingForegroundDispatches(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 }
5017}
5018
Prabir Pradhan24047542023-11-02 17:14:59 +00005019void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005020 if (entry.injectionState) {
5021 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005023 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005024 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 }
5026 }
5027}
5028
chaviw98318de2021-05-19 16:45:23 -05005029const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005030 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005031 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005032 auto it = mWindowHandlesByDisplay.find(displayId);
5033 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005034}
5035
chaviw98318de2021-05-19 16:45:23 -05005036sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005037 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005038 if (windowHandleToken == nullptr) {
5039 return nullptr;
5040 }
5041
Prabir Pradhan16463382023-10-12 23:03:19 +00005042 if (!displayId) {
5043 // Look through all displays.
5044 for (auto& it : mWindowHandlesByDisplay) {
5045 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5046 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5047 if (windowHandle->getToken() == windowHandleToken) {
5048 return windowHandle;
5049 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005052 return nullptr;
5053 }
5054
Prabir Pradhan16463382023-10-12 23:03:19 +00005055 // Only look through the requested display.
5056 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005057 if (windowHandle->getToken() == windowHandleToken) {
5058 return windowHandle;
5059 }
5060 }
5061 return nullptr;
5062}
5063
chaviw98318de2021-05-19 16:45:23 -05005064sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5065 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005066 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005067 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5068 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005069 if (handle->getId() == windowHandle->getId() &&
5070 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005071 if (windowHandle->getInfo()->displayId != it.first) {
5072 ALOGE("Found window %s in display %" PRId32
5073 ", but it should belong to display %" PRId32,
5074 windowHandle->getName().c_str(), it.first,
5075 windowHandle->getInfo()->displayId);
5076 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005077 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 }
5080 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005081 return nullptr;
5082}
5083
chaviw98318de2021-05-19 16:45:23 -05005084sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005085 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5086 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087}
5088
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005089ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5090 auto displayInfoIt = mDisplayInfos.find(displayId);
5091 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5092 : kIdentityTransform;
5093}
5094
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005095bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5096 const MotionEntry& motionEntry) const {
5097 const WindowInfo& info = *window->getInfo();
5098
5099 // Skip spy window targets that are not valid for targeted injection.
5100 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005101 return false;
5102 }
5103
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005104 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5105 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5106 return false;
5107 }
5108
5109 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5110 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5111 window->getName().c_str());
5112 return false;
5113 }
5114
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005115 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005116 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005117 ALOGW("Not sending touch to %s because there's no corresponding connection",
5118 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005119 return false;
5120 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005121
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005122 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005123 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005124 return false;
5125 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005126
5127 // Drop events that can't be trusted due to occlusion
5128 const auto [x, y] = resolveTouchedPosition(motionEntry);
5129 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5130 if (!isTouchTrustedLocked(occlusionInfo)) {
5131 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005132 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005133 for (const auto& log : occlusionInfo.debugInfo) {
5134 ALOGD("%s", log.c_str());
5135 }
5136 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005137 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5138 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005139 return false;
5140 }
5141
5142 // Drop touch events if requested by input feature
5143 if (shouldDropInput(motionEntry, window)) {
5144 return false;
5145 }
5146
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005147 // Ignore touches if stylus is down anywhere on screen
5148 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5149 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5150 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5151 return false;
5152 }
5153
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005154 return true;
5155}
5156
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005157void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005158 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5159 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005160 // Remove all handles on a display if there are no windows left.
5161 mWindowHandlesByDisplay.erase(displayId);
5162 return;
5163 }
5164
5165 // Since we compare the pointer of input window handles across window updates, we need
5166 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005167 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5168 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5169 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005170 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 }
5172
chaviw98318de2021-05-19 16:45:23 -05005173 std::vector<sp<WindowInfoHandle>> newHandles;
5174 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005175 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005176 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005177 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005178 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005179 const bool canReceiveInput =
5180 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5181 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005182 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005183 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005184 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005185 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005186 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005187 }
5188
5189 if (info->displayId != displayId) {
5190 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5191 handle->getName().c_str(), displayId, info->displayId);
5192 continue;
5193 }
5194
Robert Carredd13602020-04-13 17:24:34 -07005195 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5196 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005197 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005198 oldHandle->updateFrom(handle);
5199 newHandles.push_back(oldHandle);
5200 } else {
5201 newHandles.push_back(handle);
5202 }
5203 }
5204
5205 // Insert or replace
5206 mWindowHandlesByDisplay[displayId] = newHandles;
5207}
5208
Arthur Hungb92218b2018-08-14 12:00:21 +08005209/**
5210 * Called from InputManagerService, update window handle list by displayId that can receive input.
5211 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5212 * If set an empty list, remove all handles from the specific display.
5213 * For focused handle, check if need to change and send a cancel event to previous one.
5214 * For removed handle, check if need to send a cancel event if already in touch.
5215 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005216void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005217 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005218 if (DEBUG_FOCUS) {
5219 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005220 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005221 windowList += iwh->getName() + " ";
5222 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005223 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225
Prabir Pradhand65552b2021-10-07 11:23:50 -07005226 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005227 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005228 const WindowInfo& info = *window->getInfo();
5229
5230 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005231 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005232 if (noInputWindow && window->getToken() != nullptr) {
5233 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5234 window->getName().c_str());
5235 window->releaseChannel();
5236 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005237
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005238 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005239 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5240 !info.inputConfig.test(
5241 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005242 "%s has feature SPY, but is not a trusted overlay.",
5243 window->getName().c_str());
5244
Prabir Pradhand65552b2021-10-07 11:23:50 -07005245 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005246 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5247 !info.inputConfig.test(
5248 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005249 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5250 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005251 }
5252
Arthur Hung72d8dc32020-03-28 00:48:39 +00005253 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005254 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005255 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256
chaviw98318de2021-05-19 16:45:23 -05005257 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005258
chaviw98318de2021-05-19 16:45:23 -05005259 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005260
Vishnu Nairc519ff72021-01-21 08:23:08 -08005261 std::optional<FocusResolver::FocusChanges> changes =
5262 mFocusResolver.setInputWindows(displayId, windowHandles);
5263 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005264 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005267 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5268 mTouchStatesByDisplay.find(displayId);
5269 if (stateIt != mTouchStatesByDisplay.end()) {
5270 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005271 for (size_t i = 0; i < state.windows.size();) {
5272 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005273 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005274 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5275 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005276 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5277 "touched window was removed");
5278 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5279 // Since we are about to drop the touch, cancel the events for the wallpaper as
5280 // well.
5281 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5282 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5283 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5284 if (const auto& ww = state.getWallpaperWindow(); ww) {
5285 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005288 state.windows.erase(state.windows.begin() + i);
5289 } else {
5290 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 }
5292 }
arthurhungb89ccb02020-12-30 16:19:01 +08005293
arthurhung6d4bed92021-03-17 11:59:33 +08005294 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005295 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005296 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005297 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005298 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005299 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5300 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005301 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005302 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005303 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005304
Arthur Hung72d8dc32020-03-28 00:48:39 +00005305 // Release information for windows that are no longer present.
5306 // This ensures that unused input channels are released promptly.
5307 // Otherwise, they might stick around until the window handle is destroyed
5308 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005309 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005310 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005311 if (DEBUG_FOCUS) {
5312 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005313 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005314 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005315 }
chaviw291d88a2019-02-14 10:33:58 -08005316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317}
5318
5319void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005320 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005321 if (DEBUG_FOCUS) {
5322 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5323 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5324 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005325 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005326 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005327 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 } // release lock
5329
5330 // Wake up poll loop since it may need to make new input dispatching choices.
5331 mLooper->wake();
5332}
5333
Vishnu Nair599f1412021-06-21 10:39:58 -07005334void InputDispatcher::setFocusedApplicationLocked(
5335 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5336 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5337 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5338
5339 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5340 return; // This application is already focused. No need to wake up or change anything.
5341 }
5342
5343 // Set the new application handle.
5344 if (inputApplicationHandle != nullptr) {
5345 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5346 } else {
5347 mFocusedApplicationHandlesByDisplay.erase(displayId);
5348 }
5349
5350 // No matter what the old focused application was, stop waiting on it because it is
5351 // no longer focused.
5352 resetNoFocusedWindowTimeoutLocked();
5353}
5354
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005355void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5356 if (interval.count() < 0) {
5357 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5358 }
5359 std::scoped_lock _l(mLock);
5360 mMinTimeBetweenUserActivityPokes = interval;
5361}
5362
Tiger Huang721e26f2018-07-24 22:26:19 +08005363/**
5364 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5365 * the display not specified.
5366 *
5367 * We track any unreleased events for each window. If a window loses the ability to receive the
5368 * released event, we will send a cancel event to it. So when the focused display is changed, we
5369 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5370 * display. The display-specified events won't be affected.
5371 */
5372void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005373 if (DEBUG_FOCUS) {
5374 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5375 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005377 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005378
5379 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005380 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005381 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005382 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005383 const auto windowHandle =
5384 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5385 if (windowHandle == nullptr) {
5386 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005388 CancelationOptions
5389 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5390 "The display which contains this window no longer has focus.");
5391 options.displayId = ADISPLAY_ID_NONE;
5392 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005393 }
5394 mFocusedDisplayId = displayId;
5395
Chris Ye3c2d6f52020-08-09 10:39:48 -07005396 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005397 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005398 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005399
Vishnu Nairad321cd2020-08-20 16:40:21 -07005400 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005402 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005403 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005404 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005405 }
5406 }
5407 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005408 } // release lock
5409
5410 // Wake up poll loop since it may need to make new input dispatching choices.
5411 mLooper->wake();
5412}
5413
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005415 if (DEBUG_FOCUS) {
5416 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
5419 bool changed;
5420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422
5423 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5424 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005425 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 }
5427
5428 if (mDispatchEnabled && !enabled) {
5429 resetAndDropEverythingLocked("dispatcher is being disabled");
5430 }
5431
5432 mDispatchEnabled = enabled;
5433 mDispatchFrozen = frozen;
5434 changed = true;
5435 } else {
5436 changed = false;
5437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 } // release lock
5439
5440 if (changed) {
5441 // Wake up poll loop since it may need to make new input dispatching choices.
5442 mLooper->wake();
5443 }
5444}
5445
5446void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005447 if (DEBUG_FOCUS) {
5448 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450
5451 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005452 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453
5454 if (mInputFilterEnabled == enabled) {
5455 return;
5456 }
5457
5458 mInputFilterEnabled = enabled;
5459 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5460 } // release lock
5461
5462 // Wake up poll loop since there might be work to do to drop everything.
5463 mLooper->wake();
5464}
5465
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005466bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005467 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005468 bool needWake = false;
5469 {
5470 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005471 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005472 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005473 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005474 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5475 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005476 mTouchModePerDisplay.count(displayId) == 0
5477 ? "not set"
5478 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5479
Antonio Kantek15beb512022-06-13 22:35:41 +00005480 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5481 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005482 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005483 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005484 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005485 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5486 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005487 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005488 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005489 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005490 return false;
5491 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005492 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005493 mTouchModePerDisplay[displayId] = inTouchMode;
5494 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5495 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005496 needWake = enqueueInboundEventLocked(std::move(entry));
5497 } // release lock
5498
5499 if (needWake) {
5500 mLooper->wake();
5501 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005502 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005503}
5504
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005505bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005506 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5507 if (focusedToken == nullptr) {
5508 return false;
5509 }
5510 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5511 return isWindowOwnedBy(windowHandle, pid, uid);
5512}
5513
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005514bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005515 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5516 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5517 const sp<WindowInfoHandle> windowHandle =
5518 getWindowHandleLocked(connectionToken);
5519 return isWindowOwnedBy(windowHandle, pid, uid);
5520 }) != mInteractionConnectionTokens.end();
5521}
5522
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005523void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5524 if (opacity < 0 || opacity > 1) {
5525 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5526 return;
5527 }
5528
5529 std::scoped_lock lock(mLock);
5530 mMaximumObscuringOpacityForTouch = opacity;
5531}
5532
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005533std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5534InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005535 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5536 for (TouchedWindow& w : state.windows) {
5537 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005538 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005539 }
5540 }
5541 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005542 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005543}
5544
Prabir Pradhan367f3432024-02-13 23:05:58 +00005545bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5546 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005547 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005548 if (DEBUG_FOCUS) {
5549 ALOGD("Trivial transfer to same window.");
5550 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005551 return true;
5552 }
5553
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005555 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556
Arthur Hungabbb9d82021-09-01 14:52:30 +00005557 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005558 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005559
Arthur Hungabbb9d82021-09-01 14:52:30 +00005560 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005561 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 return false;
5563 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005564 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5565 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005566 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5567 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005568 return false;
5569 }
5570 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005571
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005572 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5573 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5574 if (!toWindowHandle) {
5575 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005576 return false;
5577 }
5578
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005579 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005580 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005581 touchedWindow->windowHandle->getName().c_str(),
5582 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 }
5584
Arthur Hungabbb9d82021-09-01 14:52:30 +00005585 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005586 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005587 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005588 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589
Arthur Hungabbb9d82021-09-01 14:52:30 +00005590 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005591 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005592 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005593 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005594 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005595 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005596 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005597 // Transferring touch focus using this API should not effect the focused window.
5598 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005599 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005600 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601
Arthur Hungabbb9d82021-09-01 14:52:30 +00005602 // Store the dragging window.
5603 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005604 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005605 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5606 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005607 return false;
5608 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005609 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005610 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005611 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
5613
Arthur Hungabbb9d82021-09-01 14:52:30 +00005614 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005615 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5616 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005617 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005618 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005619 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5620 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005621 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005622 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5623 newTargetFlags);
5624
5625 // Check if the wallpaper window should deliver the corresponding event.
5626 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005627 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 } // release lock
5630
5631 // Wake up poll loop since it may need to make new input dispatching choices.
5632 mLooper->wake();
5633 return true;
5634}
5635
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005636/**
5637 * Get the touched foreground window on the given display.
5638 * Return null if there are no windows touched on that display, or if more than one foreground
5639 * window is being touched.
5640 */
5641sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5642 auto stateIt = mTouchStatesByDisplay.find(displayId);
5643 if (stateIt == mTouchStatesByDisplay.end()) {
5644 ALOGI("No touch state on display %" PRId32, displayId);
5645 return nullptr;
5646 }
5647
5648 const TouchState& state = stateIt->second;
5649 sp<WindowInfoHandle> touchedForegroundWindow;
5650 // If multiple foreground windows are touched, return nullptr
5651 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005652 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005653 if (touchedForegroundWindow != nullptr) {
5654 ALOGI("Two or more foreground windows: %s and %s",
5655 touchedForegroundWindow->getName().c_str(),
5656 window.windowHandle->getName().c_str());
5657 return nullptr;
5658 }
5659 touchedForegroundWindow = window.windowHandle;
5660 }
5661 }
5662 return touchedForegroundWindow;
5663}
5664
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005665// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005666bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5667 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005668 sp<IBinder> fromToken;
5669 { // acquire lock
5670 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005671 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005672 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005673 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5674 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005675 return false;
5676 }
5677
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005678 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5679 if (from == nullptr) {
5680 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5681 return false;
5682 }
5683
5684 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005685 } // release lock
5686
Prabir Pradhan367f3432024-02-13 23:05:58 +00005687 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005688}
5689
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005691 if (DEBUG_FOCUS) {
5692 ALOGD("Resetting and dropping all events (%s).", reason);
5693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694
Michael Wrightfb04fd52022-11-24 22:31:11 +00005695 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 synthesizeCancelationEventsForAllConnectionsLocked(options);
5697
5698 resetKeyRepeatLocked();
5699 releasePendingEventLocked();
5700 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005701 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005703 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005704 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705}
5706
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005707void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005708 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 dumpDispatchStateLocked(dump);
5710
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 std::istringstream stream(dump);
5712 std::string line;
5713
5714 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005715 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 }
5717}
5718
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005719std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005720 std::string dump;
5721
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005722 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5723 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005724
5725 std::string windowName = "None";
5726 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005727 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005728 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5729 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5730 : "token has capture without window";
5731 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005732 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005733
5734 return dump;
5735}
5736
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005737void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005738 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5739 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5740 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005741 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742
Tiger Huang721e26f2018-07-24 22:26:19 +08005743 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5744 dump += StringPrintf(INDENT "FocusedApplications:\n");
5745 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5746 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005747 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005748 const std::chrono::duration timeout =
5749 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005750 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005751 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005752 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005755 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005757
Vishnu Nairc519ff72021-01-21 08:23:08 -08005758 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005759 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005761 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005762 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005763 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005764 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5765 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
5767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005768 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770
arthurhung6d4bed92021-03-17 11:59:33 +08005771 if (mDragState) {
5772 dump += StringPrintf(INDENT "DragState:\n");
5773 mDragState->dump(dump, INDENT2);
5774 }
5775
Arthur Hungb92218b2018-08-14 12:00:21 +08005776 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005777 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5778 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5779 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5780 const auto& displayInfo = it->second;
5781 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5782 displayInfo.logicalHeight);
5783 displayInfo.transform.dump(dump, "transform", INDENT4);
5784 } else {
5785 dump += INDENT2 "No DisplayInfo found!\n";
5786 }
5787
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005788 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005789 dump += INDENT2 "Windows:\n";
5790 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005791 dump += StringPrintf(INDENT3 "%zu: %s", i,
5792 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005793 }
5794 } else {
5795 dump += INDENT2 "Windows: <none>\n";
5796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797 }
5798 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005799 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 }
5801
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 if (!mGlobalMonitorsByDisplay.empty()) {
5803 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5804 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005805 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005808 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 }
5810
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005811 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812
5813 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005814 if (!mRecentQueue.empty()) {
5815 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005816 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005817 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005818 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005819 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820 }
5821 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005822 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 }
5824
5825 // Dump event currently being dispatched.
5826 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "PendingEvent:\n";
5828 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005829 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005830 dump += StringPrintf(", age=%" PRId64 "ms\n",
5831 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005833 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005834 }
5835
5836 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005837 if (!mInboundQueue.empty()) {
5838 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005839 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005840 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005841 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005842 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 }
5844 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005845 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 }
5847
Prabir Pradhancef936d2021-07-21 16:17:52 +00005848 if (!mCommandQueue.empty()) {
5849 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5850 } else {
5851 dump += INDENT "CommandQueue: <empty>\n";
5852 }
5853
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005854 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005855 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005856 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005857 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005858 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005859 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005860 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005861 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005862 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005864 if (!connection->outboundQueue.empty()) {
5865 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5866 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005867 dump += dumpQueue(connection->outboundQueue, currentTime);
5868
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005870 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871 }
5872
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005873 if (!connection->waitQueue.empty()) {
5874 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5875 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005876 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005878 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005880 std::string inputStateDump = streamableToString(connection->inputState);
5881 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005882 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005883 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 }
5886 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005887 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 }
5889
Antonio Kantek15beb512022-06-13 22:35:41 +00005890 if (!mTouchModePerDisplay.empty()) {
5891 dump += INDENT "TouchModePerDisplay:\n";
5892 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5893 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5894 std::to_string(touchMode).c_str());
5895 }
5896 } else {
5897 dump += INDENT "TouchModePerDisplay: <none>\n";
5898 }
5899
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005900 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005901 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5902 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5903 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005904 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005905 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005906 dump += INDENT "InputTracer: ";
5907 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908}
5909
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005910void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005911 const size_t numMonitors = monitors.size();
5912 for (size_t i = 0; i < numMonitors; i++) {
5913 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005914 const std::shared_ptr<Connection>& connection = monitor.connection;
5915 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005916 dump += "\n";
5917 }
5918}
5919
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005920class LooperEventCallback : public LooperCallback {
5921public:
5922 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5923 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5924
5925private:
5926 std::function<int(int events)> mCallback;
5927};
5928
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005929Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005930 if (DEBUG_CHANNEL_CREATION) {
5931 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005934 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005935 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005936 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005937
5938 if (result) {
5939 return base::Error(result) << "Failed to open input channel pair with name " << name;
5940 }
5941
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005943 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005944 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005945 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005946 std::shared_ptr<Connection> connection =
5947 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5948 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005950 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5951 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005952 ALOGE("Created a new connection, but the token %p is already known", token.get());
5953 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005954
5955 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5956 this, std::placeholders::_1, token);
5957
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005958 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005959 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 } // release lock
5961
5962 // Wake the looper because some connections have changed.
5963 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005964 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965}
5966
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005967Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005968 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005969 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005970 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005971 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005972 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005973 if (result) {
5974 return base::Error(result) << "Failed to open input channel pair with name " << name;
5975 }
5976
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 { // acquire lock
5978 std::scoped_lock _l(mLock);
5979
5980 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005981 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5982 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005983 }
5984
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005985 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005986 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005987 std::shared_ptr<Connection> connection =
5988 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5989 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005990
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005991 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5992 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005993 ALOGE("Created a new connection, but the token %p is already known", token.get());
5994 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005995
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005996 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5997 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005998
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005999 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006000
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006001 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006002 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006003 }
Garfield Tan15601662020-09-22 15:32:38 -07006004
Michael Wright3dd60e22019-03-27 22:06:44 +00006005 // Wake the looper because some connections have changed.
6006 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006007 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006008}
6009
Garfield Tan15601662020-09-22 15:32:38 -07006010status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006012 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013
Harry Cutts33476232023-01-30 19:57:29 +00006014 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 if (status) {
6016 return status;
6017 }
6018 } // release lock
6019
6020 // Wake the poll loop because removing the connection may have changed the current
6021 // synchronization state.
6022 mLooper->wake();
6023 return OK;
6024}
6025
Garfield Tan15601662020-09-22 15:32:38 -07006026status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6027 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006028 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006029 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006030 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 return BAD_VALUE;
6032 }
6033
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006034 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006035
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006037 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 }
6039
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006040 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041
6042 nsecs_t currentTime = now();
6043 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6044
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006045 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 return OK;
6047}
6048
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006049void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006050 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6051 auto& [displayId, monitors] = *it;
6052 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006053 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006054 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006055
Michael Wright3dd60e22019-03-27 22:06:44 +00006056 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006057 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006058 } else {
6059 ++it;
6060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 }
6062}
6063
Michael Wright3dd60e22019-03-27 22:06:44 +00006064status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006065 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006066 return pilferPointersLocked(token);
6067}
Michael Wright3dd60e22019-03-27 22:06:44 +00006068
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006069status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006070 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6071 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006072 LOG(WARNING)
6073 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006075 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006076
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006077 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006078 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006079 LOG(WARNING)
6080 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6081 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082 return BAD_VALUE;
6083 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006084 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006085 if (deviceIds.empty()) {
6086 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006087 return BAD_VALUE;
6088 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006089
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006090 for (const DeviceId deviceId : deviceIds) {
6091 TouchState& state = *statePtr;
6092 TouchedWindow& window = *windowPtr;
6093 // Send cancel events to all the input channels we're stealing from.
6094 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6095 "input channel stole pointer stream");
6096 options.deviceId = deviceId;
6097 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006098 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6099 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006100 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006101
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006102 std::string canceledWindows;
6103 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006104 if (w.windowHandle->getToken() != token) {
6105 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006106 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006107 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006108 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006109 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006110 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006111 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006112 << " is stealing input gesture for device " << deviceId << " from "
6113 << canceledWindows;
6114
6115 // Prevent the gesture from being sent to any other windows.
6116 // This only blocks relevant pointers to be sent to other windows
6117 window.addPilferingPointers(deviceId, pointerIds);
6118
6119 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006120 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006121 return OK;
6122}
6123
Prabir Pradhan99987712020-11-10 18:43:05 -08006124void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6125 { // acquire lock
6126 std::scoped_lock _l(mLock);
6127 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006128 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006129 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6130 windowHandle != nullptr ? windowHandle->getName().c_str()
6131 : "token without window");
6132 }
6133
Vishnu Nairc519ff72021-01-21 08:23:08 -08006134 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006135 if (focusedToken != windowToken) {
6136 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6137 enabled ? "enable" : "disable");
6138 return;
6139 }
6140
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006141 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006142 ALOGW("Ignoring request to %s Pointer Capture: "
6143 "window has %s requested pointer capture.",
6144 enabled ? "enable" : "disable", enabled ? "already" : "not");
6145 return;
6146 }
6147
Christine Franksb768bb42021-11-29 12:11:31 -08006148 if (enabled) {
6149 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6150 mIneligibleDisplaysForPointerCapture.end(),
6151 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6152 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6153 return;
6154 }
6155 }
6156
Prabir Pradhan99987712020-11-10 18:43:05 -08006157 setPointerCaptureLocked(enabled);
6158 } // release lock
6159
6160 // Wake the thread to process command entries.
6161 mLooper->wake();
6162}
6163
Christine Franksb768bb42021-11-29 12:11:31 -08006164void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6165 { // acquire lock
6166 std::scoped_lock _l(mLock);
6167 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6168 if (!isEligible) {
6169 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6170 }
6171 } // release lock
6172}
6173
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006174std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006175 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006176 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006177 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006178 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006179 }
6180 }
6181 }
6182 return std::nullopt;
6183}
6184
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006185std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6186 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006187 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006188 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006189 }
6190
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006191 for (const auto& [token, connection] : mConnectionsByToken) {
6192 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006193 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 }
6195 }
Robert Carr4e670e52018-08-15 13:26:12 -07006196
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006197 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198}
6199
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006200std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006201 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006202 if (connection == nullptr) {
6203 return "<nullptr>";
6204 }
6205 return connection->getInputChannelName();
6206}
6207
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006208void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006209 mAnrTracker.eraseToken(connection->getToken());
6210 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006211}
6212
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006214 const std::shared_ptr<Connection>& connection,
6215 uint32_t seq, bool handled,
6216 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006217 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006218 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006219
6220 { // Start critical section
6221 auto dispatchEntryIt =
6222 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6223 [seq](auto& e) { return e->seq == seq; });
6224 if (dispatchEntryIt == connection->waitQueue.end()) {
6225 return;
6226 }
6227
6228 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6229
6230 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6231 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006232 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006233 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6234 }
6235 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006236 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006237 dispatchEntry.deliveryTime, consumeTime, finishTime);
6238 }
6239
6240 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006241 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6242 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006243 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006244 }
6245 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006246
6247 // Dequeue the event and start the next cycle.
6248 // Because the lock might have been released, it is possible that the
6249 // contents of the wait queue to have been drained, so we need to double-check
6250 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006251 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6252 [seq](auto& e) { return e->seq == seq; });
6253 if (entryIt != connection->waitQueue.end()) {
6254 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6255 connection->waitQueue.erase(entryIt);
6256
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006257 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6259 if (!connection->responsive) {
6260 connection->responsive = isConnectionResponsive(*connection);
6261 if (connection->responsive) {
6262 // The connection was unresponsive, and now it's responsive.
6263 processConnectionResponsiveLocked(*connection);
6264 }
6265 }
6266 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006267 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006268 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6269 // Only dispatch fallbacks if there is a window for the connection.
6270 if (windowHandle != nullptr) {
6271 const auto inputTarget =
6272 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6273 dispatchEntry->targetFlags,
6274 fallbackKeyEntry->downTime);
6275 if (inputTarget.has_value()) {
6276 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6277 *inputTarget);
6278 }
6279 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006281 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282 }
6283
6284 // Start the next dispatch cycle for this connection.
6285 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286}
6287
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6289 const sp<IBinder>& newToken) {
6290 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6291 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006292 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 };
6294 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295}
6296
Prabir Pradhancef936d2021-07-21 16:17:52 +00006297void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6298 auto command = [this, token, x, y]() REQUIRES(mLock) {
6299 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006300 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 };
6302 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006303}
6304
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006305void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006306 if (connection == nullptr) {
6307 LOG_ALWAYS_FATAL("Caller must check for nullness");
6308 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006309 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6310 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006312 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006313 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314 return;
6315 }
6316 /**
6317 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6318 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6319 * has changed. This could cause newer entries to time out before the already dispatched
6320 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6321 * processes the events linearly. So providing information about the oldest entry seems to be
6322 * most useful.
6323 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006324 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6325 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006326 std::string reason =
6327 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006328 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006329 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006330 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006331 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006332 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006333
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006334 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6335
6336 // Stop waking up for events on this connection, it is already unresponsive
6337 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006338}
6339
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006340void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6341 std::string reason =
6342 StringPrintf("%s does not have a focused window", application->getName().c_str());
6343 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006344
Yabin Cui8eb9c552023-06-08 18:05:07 +00006345 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006346 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006347 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006348 };
6349 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006350}
6351
chaviw98318de2021-05-19 16:45:23 -05006352void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006353 const std::string& reason) {
6354 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6355 updateLastAnrStateLocked(windowLabel, reason);
6356}
6357
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006358void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6359 const std::string& reason) {
6360 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006361 updateLastAnrStateLocked(windowLabel, reason);
6362}
6363
6364void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6365 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006367 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 struct tm tm;
6369 localtime_r(&t, &tm);
6370 char timestr[64];
6371 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006372 mLastAnrState.clear();
6373 mLastAnrState += INDENT "ANR:\n";
6374 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006375 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6376 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006377 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378}
6379
Prabir Pradhancef936d2021-07-21 16:17:52 +00006380void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006381 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006382 const KeyEvent event = createKeyEvent(entry);
6383 nsecs_t delay = 0;
6384 { // release lock
6385 scoped_unlock unlock(mLock);
6386 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006387 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006388 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6389 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6390 std::to_string(t.duration().count()).c_str());
6391 }
6392 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
6394 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006395 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006396 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006397 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006399 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006400 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402}
6403
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006405 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006406 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006407 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006408 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006409 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006410 };
6411 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006412}
6413
Prabir Pradhanedd96402022-02-15 01:46:16 -08006414void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006415 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006416 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006417 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006418 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006419 };
6420 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006421}
6422
6423/**
6424 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6425 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6426 * command entry to the command queue.
6427 */
6428void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6429 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006430 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006431 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006432 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006433 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006434 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006435 pid = findMonitorPidByTokenLocked(connectionToken);
6436 } else {
6437 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006438 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006439 reason.c_str());
6440 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6441 if (handle != nullptr) {
6442 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006443 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006444 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006445 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006446}
6447
6448/**
6449 * Tell the policy that a connection has become responsive so that it can stop ANR.
6450 */
6451void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006452 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006453 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006454 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006455 pid = findMonitorPidByTokenLocked(connectionToken);
6456 } else {
6457 // The connection is a window
6458 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6459 if (handle != nullptr) {
6460 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006461 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006462 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006463 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006464}
6465
Prabir Pradhan24047542023-11-02 17:14:59 +00006466std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006467 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006468 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006469 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006470 if (!handled) {
6471 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006472 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006473 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006474 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006476
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477 // Get the fallback key state.
6478 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006479 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006481 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 connection->inputState.removeFallbackKey(originalKeyCode);
6483 }
6484
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006485 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486 // If the application handles the original key for which we previously
6487 // generated a fallback or if the window is not a foreground window,
6488 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006489 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006491 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6492 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6493 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6494 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6495 keyEntry.policyFlags);
6496 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006497 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499
6500 mLock.unlock();
6501
Prabir Pradhana41d2442023-04-20 21:30:40 +00006502 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006503 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6504 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006505 unhandledKeyFallback) {
6506 event = *unhandledKeyFallback;
6507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508
6509 mLock.lock();
6510
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006511 // Cancel the fallback key, but only if we still have a window for the channel.
6512 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006513 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006514 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6515 if (windowHandle != nullptr) {
6516 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6517 "application handled the original non-fallback key "
6518 "or is no longer a foreground target, "
6519 "canceling previously dispatched fallback key");
6520 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006521 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006523 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 connection->inputState.removeFallbackKey(originalKeyCode);
6525 }
6526 } else {
6527 // If the application did not handle a non-fallback key, first check
6528 // that we are in a good state to perform unhandled key event processing
6529 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006530 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006531 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006532 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6533 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6534 "since this is not an initial down. "
6535 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6536 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6537 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006538 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006541 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006542 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6543 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6544 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6545 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6546 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006547 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006548
6549 mLock.unlock();
6550
Prabir Pradhana41d2442023-04-20 21:30:40 +00006551 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006552 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6553 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006554 fb) {
6555 fallback = true;
6556 event = *fb;
6557 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558
6559 mLock.lock();
6560
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006561 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006563 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006564 }
6565
6566 // Latch the fallback keycode for this key on an initial down.
6567 // The fallback keycode cannot change at any other point in the lifecycle.
6568 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006570 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006571 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006572 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006573 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006574 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006575 }
6576
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006577 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006578
6579 // Cancel the fallback key if the policy decides not to send it anymore.
6580 // We will continue to dispatch the key to the policy but we will no
6581 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006582 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6583 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006584 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6585 if (fallback) {
6586 ALOGD("Unhandled key event: Policy requested to send key %d"
6587 "as a fallback for %d, but on the DOWN it had requested "
6588 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006589 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006590 } else {
6591 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6592 "but on the DOWN it had requested to send %d. "
6593 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006594 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006595 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006596 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006597
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006598 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6599 if (windowHandle != nullptr) {
6600 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6601 "canceling fallback, policy no longer desires it");
6602 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006603 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006604 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006605
6606 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006607 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006608 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006609 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610 }
6611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006613 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6614 {
6615 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006616 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006617 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006618 for (const auto& [key, value] : fallbackKeys) {
6619 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006620 }
6621 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6622 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006624 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006625
6626 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006627 // Return the fallback key that we want dispatched to the channel.
6628 std::unique_ptr<KeyEntry> newEntry =
6629 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6630 event.getEventTime(), event.getDeviceId(),
6631 event.getSource(), event.getDisplayId(),
6632 keyEntry.policyFlags, keyEntry.action,
6633 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6634 *fallbackKeyCode, event.getScanCode(),
6635 event.getMetaState(), event.getRepeatCount(),
6636 event.getDownTime());
Prabir Pradhana67623c2024-02-21 06:57:36 +00006637 if (mTracer) {
6638 newEntry->traceTracker =
6639 mTracer->traceDerivedEvent(*newEntry, *keyEntry.traceTracker);
6640 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006641 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6642 ALOGD("Unhandled key event: Dispatching fallback key. "
6643 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006644 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006645 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006646 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006647 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006648 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6649 ALOGD("Unhandled key event: No fallback key.");
6650 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006651
6652 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006653 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006654 }
6655 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006656 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006657}
6658
Michael Wrightd02c5b62014-02-10 15:10:22 -08006659void InputDispatcher::traceInboundQueueLengthLocked() {
6660 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006661 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006662 }
6663}
6664
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006665void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666 if (ATRACE_ENABLED()) {
6667 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006668 snprintf(counterName, sizeof(counterName), "oq:%s",
6669 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006670 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006671 }
6672}
6673
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006674void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675 if (ATRACE_ENABLED()) {
6676 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006677 snprintf(counterName, sizeof(counterName), "wq:%s",
6678 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006679 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006680 }
6681}
6682
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006683void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006684 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006685
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006686 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006687 dumpDispatchStateLocked(dump);
6688
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006689 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006690 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006691 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006692 }
6693}
6694
6695void InputDispatcher::monitor() {
6696 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006697 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006698 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006699 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006700}
6701
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006702/**
6703 * Wake up the dispatcher and wait until it processes all events and commands.
6704 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6705 * this method can be safely called from any thread, as long as you've ensured that
6706 * the work you are interested in completing has already been queued.
6707 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006708bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006709 /**
6710 * Timeout should represent the longest possible time that a device might spend processing
6711 * events and commands.
6712 */
6713 constexpr std::chrono::duration TIMEOUT = 100ms;
6714 std::unique_lock lock(mLock);
6715 mLooper->wake();
6716 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6717 return result == std::cv_status::no_timeout;
6718}
6719
Vishnu Naire798b472020-07-23 13:52:21 -07006720/**
6721 * Sets focus to the window identified by the token. This must be called
6722 * after updating any input window handles.
6723 *
6724 * Params:
6725 * request.token - input channel token used to identify the window that should gain focus.
6726 * request.focusedToken - the token that the caller expects currently to be focused. If the
6727 * specified token does not match the currently focused window, this request will be dropped.
6728 * If the specified focused token matches the currently focused window, the call will succeed.
6729 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6730 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6731 * when requesting the focus change. This determines which request gets
6732 * precedence if there is a focus change request from another source such as pointer down.
6733 */
Vishnu Nair958da932020-08-21 17:12:37 -07006734void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6735 { // acquire lock
6736 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006737 std::optional<FocusResolver::FocusChanges> changes =
6738 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6739 if (changes) {
6740 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006741 }
6742 } // release lock
6743 // Wake up poll loop since it may need to make new input dispatching choices.
6744 mLooper->wake();
6745}
6746
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006747void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6748 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006749 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006750 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6751 ? removedFocusedWindowHandle
6752 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6753 if (resolvedWindow == nullptr) {
6754 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006755 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006756 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6757 "focus left window");
6758 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6759 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006760 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006761 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006762 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006763 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006764 }
6765
Prabir Pradhan99987712020-11-10 18:43:05 -08006766 // If a window has pointer capture, then it must have focus. We need to ensure that this
6767 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6768 // If the window loses focus before it loses pointer capture, then the window can be in a state
6769 // where it has pointer capture but not focus, violating the contract. Therefore we must
6770 // dispatch the pointer capture event before the focus event. Since focus events are added to
6771 // the front of the queue (above), we add the pointer capture event to the front of the queue
6772 // after the focus events are added. This ensures the pointer capture event ends up at the
6773 // front.
6774 disablePointerCaptureForcedLocked();
6775
Vishnu Nairc519ff72021-01-21 08:23:08 -08006776 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006777 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006778 }
6779}
Vishnu Nair958da932020-08-21 17:12:37 -07006780
Prabir Pradhan99987712020-11-10 18:43:05 -08006781void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006782 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006783 return;
6784 }
6785
6786 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6787
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006788 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006789 setPointerCaptureLocked(false);
6790 }
6791
6792 if (!mWindowTokenWithPointerCapture) {
6793 // No need to send capture changes because no window has capture.
6794 return;
6795 }
6796
6797 if (mPendingEvent != nullptr) {
6798 // Move the pending event to the front of the queue. This will give the chance
6799 // for the pending event to be dropped if it is a captured event.
6800 mInboundQueue.push_front(mPendingEvent);
6801 mPendingEvent = nullptr;
6802 }
6803
6804 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006805 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006806 mInboundQueue.push_front(std::move(entry));
6807}
6808
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006809void InputDispatcher::setPointerCaptureLocked(bool enable) {
6810 mCurrentPointerCaptureRequest.enable = enable;
6811 mCurrentPointerCaptureRequest.seq++;
6812 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006813 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006814 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006815 };
6816 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006817}
6818
Vishnu Nair599f1412021-06-21 10:39:58 -07006819void InputDispatcher::displayRemoved(int32_t displayId) {
6820 { // acquire lock
6821 std::scoped_lock _l(mLock);
6822 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006823 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006824 setFocusedApplicationLocked(displayId, nullptr);
6825 // Call focus resolver to clean up stale requests. This must be called after input windows
6826 // have been removed for the removed display.
6827 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006828 // Reset pointer capture eligibility, regardless of previous state.
6829 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006830 // Remove the associated touch mode state.
6831 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006832 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006833 } // release lock
6834
6835 // Wake up poll loop since it may need to make new input dispatching choices.
6836 mLooper->wake();
6837}
6838
Patrick Williamsd828f302023-04-28 17:52:08 -05006839void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006840 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6841 {
6842 // acquire lock
6843 std::scoped_lock _l(mLock);
6844 logDispatchStateLocked();
6845 }
6846 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6847 result.error().message().c_str());
6848 };
chaviw15fab6f2021-06-07 14:15:52 -05006849 // The listener sends the windows as a flattened array. Separate the windows by display for
6850 // more convenient parsing.
6851 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006852 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006853 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006854 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006855 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006856
6857 { // acquire lock
6858 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006859
6860 // Ensure that we have an entry created for all existing displays so that if a displayId has
6861 // no windows, we can tell that the windows were removed from the display.
6862 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6863 handlesPerDisplay[displayId];
6864 }
6865
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006866 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006867 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006868 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6869 }
6870
6871 for (const auto& [displayId, handles] : handlesPerDisplay) {
6872 setInputWindowsLocked(handles, displayId);
6873 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006874
6875 if (update.vsyncId < mWindowInfosVsyncId) {
6876 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6877 ", current update vsync id: %" PRId64,
6878 mWindowInfosVsyncId, update.vsyncId);
6879 }
6880 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006881 }
6882 // Wake up poll loop since it may need to make new input dispatching choices.
6883 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006884}
6885
Vishnu Nair062a8672021-09-03 16:07:44 -07006886bool InputDispatcher::shouldDropInput(
6887 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006888 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6889 (windowHandle->getInfo()->inputConfig.test(
6890 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006891 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006892 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6893 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006894 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006895 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006896 windowHandle->getInfo()->displayId);
6897 return true;
6898 }
6899 return false;
6900}
6901
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006902void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006903 const gui::WindowInfosUpdate& update) {
6904 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006905}
6906
Arthur Hungdfd528e2021-12-08 13:23:04 +00006907void InputDispatcher::cancelCurrentTouch() {
6908 {
6909 std::scoped_lock _l(mLock);
6910 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006911 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006912 "cancel current touch");
6913 synthesizeCancelationEventsForAllConnectionsLocked(options);
6914
6915 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006916 }
6917 // Wake up poll loop since there might be work to do.
6918 mLooper->wake();
6919}
6920
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006921void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6922 std::scoped_lock _l(mLock);
6923 mMonitorDispatchingTimeout = timeout;
6924}
6925
Arthur Hungc539dbb2022-12-08 07:45:36 +00006926void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6927 const sp<WindowInfoHandle>& oldWindowHandle,
6928 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006929 TouchState& state, int32_t deviceId,
6930 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006931 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006932 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006933 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6934 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6935 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6936 newWindowHandle->getInfo()->inputConfig.test(
6937 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6938 const sp<WindowInfoHandle> oldWallpaper =
6939 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6940 const sp<WindowInfoHandle> newWallpaper =
6941 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6942 if (oldWallpaper == newWallpaper) {
6943 return;
6944 }
6945
6946 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006947 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006948 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006949 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006950 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006951 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006952 }
6953
6954 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006955 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6956 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006957 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006958 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006959 }
6960}
6961
6962void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6963 ftl::Flags<InputTarget::Flags> newTargetFlags,
6964 const sp<WindowInfoHandle> fromWindowHandle,
6965 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006966 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006967 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006968 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6969 fromWindowHandle->getInfo()->inputConfig.test(
6970 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6971 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6972 toWindowHandle->getInfo()->inputConfig.test(
6973 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6974
6975 const sp<WindowInfoHandle> oldWallpaper =
6976 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6977 const sp<WindowInfoHandle> newWallpaper =
6978 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6979 if (oldWallpaper == newWallpaper) {
6980 return;
6981 }
6982
6983 if (oldWallpaper != nullptr) {
6984 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6985 "transferring touch focus to another window");
6986 state.removeWindowByToken(oldWallpaper->getToken());
6987 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6988 }
6989
6990 if (newWallpaper != nullptr) {
6991 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00006992 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
6993 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006994 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6995 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006996 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006997 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006998 std::shared_ptr<Connection> wallpaperConnection =
6999 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007000 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007001 std::shared_ptr<Connection> toConnection =
7002 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007003 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7004 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7005 wallpaperFlags);
7006 }
7007 }
7008}
7009
7010sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7011 const sp<WindowInfoHandle>& windowHandle) const {
7012 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7013 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7014 bool foundWindow = false;
7015 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7016 if (!foundWindow && otherHandle != windowHandle) {
7017 continue;
7018 }
7019 if (windowHandle == otherHandle) {
7020 foundWindow = true;
7021 continue;
7022 }
7023
7024 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7025 return otherHandle;
7026 }
7027 }
7028 return nullptr;
7029}
7030
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007031void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7032 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007033 std::scoped_lock _l(mLock);
7034
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007035 mConfig.keyRepeatTimeout = timeout.count();
7036 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007037}
7038
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007039bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7040 DeviceId deviceId, int32_t pointerId) {
7041 std::scoped_lock _l(mLock);
7042 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7043 if (touchStateIt == mTouchStatesByDisplay.end()) {
7044 return false;
7045 }
7046 for (const TouchedWindow& window : touchStateIt->second.windows) {
7047 if (window.windowHandle->getToken() == token &&
7048 (window.hasTouchingPointer(deviceId, pointerId) ||
7049 window.hasHoveringPointer(deviceId, pointerId))) {
7050 return true;
7051 }
7052 }
7053 return false;
7054}
7055
Garfield Tane84e6f92019-08-29 17:28:41 -07007056} // namespace android::inputdispatcher