blob: 1725e48f7f56b59fe077897cc9c10ac9ffeed504 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000057#include "trace/ThreadedBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62#define INDENT4 " "
63
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080064using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070065using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080066using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000067using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070069using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050070using android::gui::FocusRequest;
71using android::gui::TouchOcclusionMode;
72using android::gui::WindowInfo;
73using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080074using android::os::InputEventInjectionResult;
75using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000076namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000081
Prabir Pradhandae52792023-12-15 07:36:40 +000082// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
83// flag is enabled. When the flag is changed, tracing will only be available after reboot.
84bool isInputTracingEnabled() {
85 static const std::string buildType = base::GetProperty("ro.build.type", "user");
86 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
87 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
88}
89
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000090// Create the input tracing backend that writes to perfetto from a single thread.
91std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
92 if (!isInputTracingEnabled()) {
93 return nullptr;
94 }
95 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
96 trace::impl::PerfettoBackend());
97}
98
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000099template <class Entry>
100void ensureEventTraced(const Entry& entry) {
101 if (!entry.traceTracker) {
102 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
103 }
104}
105
Prabir Pradhan052fb0b2024-02-23 21:03:12 +0000106// Helper to get a trace tracker from a traced key or motion entry.
107const std::unique_ptr<trace::EventTrackerInterface>& getTraceTracker(const EventEntry& entry) {
108 switch (entry.type) {
109 case EventEntry::Type::MOTION: {
110 const auto& motion = static_cast<const MotionEntry&>(entry);
111 ensureEventTraced(motion);
112 return motion.traceTracker;
113 }
114 case EventEntry::Type::KEY: {
115 const auto& key = static_cast<const KeyEntry&>(entry);
116 ensureEventTraced(key);
117 return key.traceTracker;
118 }
119 default: {
120 const static std::unique_ptr<trace::EventTrackerInterface> kNullTracker;
121 return kNullTracker;
122 }
123 }
124}
125
Prabir Pradhancef936d2021-07-21 16:17:52 +0000126// Temporarily releases a held mutex for the lifetime of the instance.
127// Named to match std::scoped_lock
128class scoped_unlock {
129public:
130 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
131 ~scoped_unlock() { mMutex.lock(); }
132
133private:
134 std::mutex& mMutex;
135};
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Default input dispatching timeout if there is no focused application or paused window
138// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800139const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
140 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
141 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800143// The default minimum time gap between two user activity poke events.
144const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
145
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800146const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000149constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
150
151// Log a warning when an interception call takes longer than this to process.
152constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153
154// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000155constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
156
Antonio Kantekea47acb2021-12-23 12:41:25 -0800157// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000158constexpr int LOGTAG_INPUT_INTERACTION = 62000;
159constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000160constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000161
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000162const ui::Transform kIdentityTransform;
163
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000164inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 return systemTime(SYSTEM_TIME_MONOTONIC);
166}
167
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700168inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000169 if (binder == nullptr) {
170 return "<null>";
171 }
172 return StringPrintf("%p", binder.get());
173}
174
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000175static std::string uidString(const gui::Uid& uid) {
176 return uid.toString();
177}
178
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 case AKEY_EVENT_ACTION_DOWN:
182 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700185 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700189Result<void> validateKeyEvent(int32_t action) {
190 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191}
192
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800194 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700196 case AMOTION_EVENT_ACTION_UP: {
197 if (pointerCount != 1) {
198 return Error() << "invalid pointer count " << pointerCount;
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 case AMOTION_EVENT_ACTION_HOVER_ENTER:
204 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700205 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
206 if (pointerCount < 1) {
207 return Error() << "invalid pointer count " << pointerCount;
208 }
209 return {};
210 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800211 case AMOTION_EVENT_ACTION_CANCEL:
212 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 case AMOTION_EVENT_ACTION_POINTER_DOWN:
216 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800217 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 if (index < 0) {
219 return Error() << "invalid index " << index << " for "
220 << MotionEvent::actionToString(action);
221 }
222 if (index >= pointerCount) {
223 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
224 }
225 if (pointerCount <= 1) {
226 return Error() << "invalid pointer count " << pointerCount << " for "
227 << MotionEvent::actionToString(action);
228 }
229 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700230 }
231 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
233 if (actionButton == 0) {
234 return Error() << "action button should be nonzero for "
235 << MotionEvent::actionToString(action);
236 }
237 return {};
238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700239 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 }
242}
243
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000244int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500245 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
246}
247
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700248Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
249 const PointerProperties* pointerProperties) {
250 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
251 if (!actionCheck.ok()) {
252 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 }
254 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700255 return Error() << "Motion event has invalid pointer count " << pointerCount
256 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800258 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 for (size_t i = 0; i < pointerCount; i++) {
260 int32_t id = pointerProperties[i].id;
261 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700262 return Error() << "Motion event has invalid pointer id " << id
263 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800265 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700266 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800268 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700270 return {};
271}
272
273Result<void> validateInputEvent(const InputEvent& event) {
274 switch (event.getType()) {
275 case InputEventType::KEY: {
276 const KeyEvent& key = static_cast<const KeyEvent&>(event);
277 const int32_t action = key.getAction();
278 return validateKeyEvent(action);
279 }
280 case InputEventType::MOTION: {
281 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
282 const int32_t action = motion.getAction();
283 const size_t pointerCount = motion.getPointerCount();
284 const PointerProperties* pointerProperties = motion.getPointerProperties();
285 const int32_t actionButton = motion.getActionButton();
286 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
287 }
288 default: {
289 return {};
290 }
291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292}
293
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800294std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
295 std::bitset<MAX_POINTER_ID + 1> pointerIds;
296 for (const PointerProperties& pointer : pointers) {
297 pointerIds.set(pointer.id);
298 }
299 return pointerIds;
300}
301
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000302std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000304 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 }
306
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000307 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 bool first = true;
309 Region::const_iterator cur = region.begin();
310 Region::const_iterator const tail = region.end();
311 while (cur != tail) {
312 if (first) {
313 first = false;
314 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800315 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800317 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318 cur++;
319 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000320 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321}
322
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000323std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
324 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500325 constexpr size_t maxEntries = 50; // max events to print
326 constexpr size_t skipBegin = maxEntries / 2;
327 const size_t skipEnd = queue.size() - maxEntries / 2;
328 // skip from maxEntries / 2 ... size() - maxEntries/2
329 // only print from 0 .. skipBegin and then from skipEnd .. size()
330
331 std::string dump;
332 for (size_t i = 0; i < queue.size(); i++) {
333 const DispatchEntry& entry = *queue[i];
334 if (i >= skipBegin && i < skipEnd) {
335 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
336 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
337 continue;
338 }
339 dump.append(INDENT4);
340 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000341 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
342 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500343 ns2ms(currentTime - entry.eventEntry->eventTime));
344 if (entry.deliveryTime != 0) {
345 // This entry was delivered, so add information on how long we've been waiting
346 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
347 }
348 dump.append("\n");
349 }
350 return dump;
351}
352
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700353/**
354 * Find the entry in std::unordered_map by key, and return it.
355 * If the entry is not found, return a default constructed entry.
356 *
357 * Useful when the entries are vectors, since an empty vector will be returned
358 * if the entry is not found.
359 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
360 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700361template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700363 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700364 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800365}
366
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700368 if (first == second) {
369 return true;
370 }
371
372 if (first == nullptr || second == nullptr) {
373 return false;
374 }
375
376 return first->getToken() == second->getToken();
377}
378
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000379bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000380 if (first == nullptr || second == nullptr) {
381 return false;
382 }
383 return first->applicationInfo.token != nullptr &&
384 first->applicationInfo.token == second->applicationInfo.token;
385}
386
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800387template <typename T>
388size_t firstMarkedBit(T set) {
389 // TODO: replace with std::countr_zero from <bit> when that's available
390 LOG_ALWAYS_FATAL_IF(set.none());
391 size_t i = 0;
392 while (!set.test(i)) {
393 i++;
394 }
395 return i;
396}
397
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000398std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
399 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000400 std::shared_ptr<const EventEntry> eventEntry,
401 ftl::Flags<InputTarget::Flags> inputTargetFlags,
402 int64_t vsyncId) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000403 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000404 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
405 const std::optional<int32_t> windowId =
406 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
407 // Assume the only targets that are not associated with a window are global monitors, and use
408 // the system UID for global monitors for tracing purposes.
409 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000410
411 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700412 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700413 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700414 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000415 inputTarget.globalScaleFactor, uid, vsyncId,
416 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000417 }
418
419 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
421
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000422 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000423
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000424 const ui::Transform* transform = &kIdentityTransform;
425 const ui::Transform* displayTransform = &kIdentityTransform;
426 if (zeroCoords) {
427 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
428 } else {
429 // Use the first pointer information to normalize all other pointers. This could be any
430 // pointer as long as all other pointers are normalized to the same value and the final
431 // DispatchEntry uses the transform for the normalized pointer.
432 transform =
433 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
434 const ui::Transform inverseTransform = transform->inverse();
435 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000436
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000437 // Iterate through all pointers in the event to normalize against the first.
438 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
439 PointerCoords& newCoords = pointerCoords[i];
440 const auto pointerId = motionEntry.pointerProperties[i].id;
441 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000442
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000443 newCoords.copyFrom(motionEntry.pointerCoords[i]);
444 // First, apply the current pointer's transform to update the coordinates into
445 // window space.
446 newCoords.transform(currTransform);
447 // Next, apply the inverse transform of the normalized coordinates so the
448 // current coordinates are transformed into the normalized coordinate space.
449 newCoords.transform(inverseTransform);
450 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000451 }
452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700453 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000454 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000455 motionEntry.eventTime, motionEntry.deviceId,
456 motionEntry.source, motionEntry.displayId,
457 motionEntry.policyFlags, motionEntry.action,
458 motionEntry.actionButton, motionEntry.flags,
459 motionEntry.metaState, motionEntry.buttonState,
460 motionEntry.classification, motionEntry.edgeFlags,
461 motionEntry.xPrecision, motionEntry.yPrecision,
462 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
463 motionEntry.downTime, motionEntry.pointerProperties,
464 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000465
466 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700467 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000468 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000469 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000470 return dispatchEntry;
471}
472
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500473template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000474bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500475 if (lhs == nullptr && rhs == nullptr) {
476 return true;
477 }
478 if (lhs == nullptr || rhs == nullptr) {
479 return false;
480 }
481 return *lhs == *rhs;
482}
483
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000484KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000485 KeyEvent event;
486 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
487 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
488 entry.repeatCount, entry.downTime, entry.eventTime);
489 return event;
490}
491
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000492bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 // Do not keep track of gesture monitors. They receive every event and would disproportionately
494 // affect the statistics.
495 if (connection.monitor) {
496 return false;
497 }
498 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
499 if (!connection.responsive) {
500 return false;
501 }
502 return true;
503}
504
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000505bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000506 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
507 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000508 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
509 return false;
510 }
511 // Only track latency for events that originated from hardware
512 if (eventEntry.isSynthesized()) {
513 return false;
514 }
515 const EventEntry::Type& inputEventEntryType = eventEntry.type;
516 if (inputEventEntryType == EventEntry::Type::KEY) {
517 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
518 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
519 return false;
520 }
521 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
522 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
523 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
524 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
525 return false;
526 }
527 } else {
528 // Not a key or a motion
529 return false;
530 }
531 if (!shouldReportMetricsForConnection(connection)) {
532 return false;
533 }
534 return true;
535}
536
Prabir Pradhancef936d2021-07-21 16:17:52 +0000537/**
538 * Connection is responsive if it has no events in the waitQueue that are older than the
539 * current time.
540 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000541bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000542 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000543 for (const auto& dispatchEntry : connection.waitQueue) {
544 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000545 return false;
546 }
547 }
548 return true;
549}
550
Antonio Kantekf16f2832021-09-28 04:39:20 +0000551// Returns true if the event type passed as argument represents a user activity.
552bool isUserActivityEvent(const EventEntry& eventEntry) {
553 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000554 case EventEntry::Type::CONFIGURATION_CHANGED:
555 case EventEntry::Type::DEVICE_RESET:
556 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000557 case EventEntry::Type::FOCUS:
558 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000559 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000560 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000561 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000562 case EventEntry::Type::KEY:
563 case EventEntry::Type::MOTION:
564 return true;
565 }
566}
567
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800568// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000569bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000570 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800571 const auto inputConfig = windowInfo.inputConfig;
572 if (windowInfo.displayId != displayId ||
573 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800574 return false;
575 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700576 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800577 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800578 return false;
579 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000580
581 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
582 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
583 // the window. Points on the right and bottom edges should not be inside the window, so we need
584 // to be careful about performing a hit test when the display is rotated, since the "right" and
585 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
586 // logical display in which WM determined the bounds. Perform the hit test in the logical
587 // display space to ensure these edges are considered correctly in all orientations.
588 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
589 const auto p = displayTransform.transform(x, y);
590 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800591 return false;
592 }
593 return true;
594}
595
Prabir Pradhand65552b2021-10-07 11:23:50 -0700596bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
597 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000598 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700599}
600
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800601// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000602// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
603// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
604// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800605// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000606bool canReceiveForegroundTouches(const WindowInfo& info) {
607 // A non-touchable window can still receive touch events (e.g. in the case of
608 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
609 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
610}
611
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000612bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700613 if (windowHandle == nullptr) {
614 return false;
615 }
616 const WindowInfo* windowInfo = windowHandle->getInfo();
617 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
618 return true;
619 }
620 return false;
621}
622
Prabir Pradhan5735a322022-04-11 17:23:34 +0000623// Checks targeted injection using the window's owner's uid.
624// Returns an empty string if an entry can be sent to the given window, or an error message if the
625// entry is a targeted injection whose uid target doesn't match the window owner.
626std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
627 const EventEntry& entry) {
628 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
629 // The event was not injected, or the injected event does not target a window.
630 return {};
631 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000632 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000633 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000634 return StringPrintf("No valid window target for injection into uid %s.",
635 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000636 }
637 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000638 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
639 "owned by uid %s.",
640 uid.toString().c_str(), window->getName().c_str(),
641 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000642 }
643 return {};
644}
645
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000646std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700647 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
648 // Always dispatch mouse events to cursor position.
649 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000650 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700651 }
652
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700653 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000654 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
655 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700656}
657
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700658std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
659 if (eventEntry.type == EventEntry::Type::KEY) {
660 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
661 return keyEntry.downTime;
662 } else if (eventEntry.type == EventEntry::Type::MOTION) {
663 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
664 return motionEntry.downTime;
665 }
666 return std::nullopt;
667}
668
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000669/**
670 * Compare the old touch state to the new touch state, and generate the corresponding touched
671 * windows (== input targets).
672 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
673 * If the pointer just entered the new window, produce HOVER_ENTER.
674 * For pointers remaining in the window, produce HOVER_MOVE.
675 */
676std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
677 const TouchState& newTouchState,
678 const MotionEntry& entry) {
679 std::vector<TouchedWindow> out;
680 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700681
682 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
683 // ACTION_SCROLL events should not affect the hovering pointer dispatch
684 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 }
686
687 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800688 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000689
690 std::set<sp<WindowInfoHandle>> oldWindows;
691 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800692 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000693 }
694
695 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800696 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000697
698 // If the pointer is no longer in the new window set, send HOVER_EXIT.
699 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
700 if (newWindows.find(oldWindow) == newWindows.end()) {
701 TouchedWindow touchedWindow;
702 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000703 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000704 out.push_back(touchedWindow);
705 }
706 }
707
708 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
709 TouchedWindow touchedWindow;
710 touchedWindow.windowHandle = newWindow;
711 if (oldWindows.find(newWindow) == oldWindows.end()) {
712 // Any windows that have this pointer now, and didn't have it before, should get
713 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000714 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000715 } else {
716 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700717 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700718 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000719 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
720 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700721 // The Accessibility injected touch exploration event stream
722 // has known inconsistencies, so log ERROR instead of
723 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700724 severity = android::base::LogSeverity::ERROR;
725 }
726 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700727 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000728 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000729 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800730 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000731 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
732 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
733 }
734 out.push_back(touchedWindow);
735 }
736 return out;
737}
738
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800739template <typename T>
740std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
741 left.insert(left.end(), right.begin(), right.end());
742 return left;
743}
744
Harry Cuttsb166c002023-05-09 13:06:05 +0000745// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
746// both.
747void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
748 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
749 if (!window.windowHandle->getInfo()->inputConfig.test(
750 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
751 // In addition to TouchState, erase this window from the input targets! We don't have a
752 // good way to do this today except by adding a nested loop.
753 // TODO(b/282025641): simplify this code once InputTargets are being identified
754 // separately from TouchedWindows.
755 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800756 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000757 });
758 return true;
759 }
760 return false;
761 });
762}
763
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700764/**
765 * In general, touch should be always split between windows. Some exceptions:
766 * 1. Don't split touch if all of the below is true:
767 * (a) we have an active pointer down *and*
768 * (b) a new pointer is going down that's from the same device *and*
769 * (c) the window that's receiving the current pointer does not support split touch.
770 * 2. Don't split mouse events
771 */
772bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
773 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
774 // We should never split mouse events
775 return false;
776 }
777 for (const TouchedWindow& touchedWindow : touchState.windows) {
778 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
779 // Spy windows should not affect whether or not touch is split.
780 continue;
781 }
782 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
783 continue;
784 }
785 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
786 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
787 // Wallpaper window should not affect whether or not touch is split
788 continue;
789 }
790
791 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
792 return false;
793 }
794 }
795 return true;
796}
797
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700798/**
799 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
800 */
801bool isStylusActiveInDisplay(
802 int32_t displayId,
803 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
804 const auto it = touchStatesByDisplay.find(displayId);
805 if (it == touchStatesByDisplay.end()) {
806 return false;
807 }
808 const TouchState& state = it->second;
809 return state.hasActiveStylus();
810}
811
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800812Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
813 struct HashFunction {
814 size_t operator()(const WindowInfo& info) const { return info.id; }
815 };
816
817 std::unordered_set<WindowInfo, HashFunction> windowSet;
818 for (const WindowInfo& info : update.windowInfos) {
819 const auto [_, inserted] = windowSet.insert(info);
820 if (!inserted) {
821 return Error() << "Duplicate entry for " << info;
822 }
823 }
824 return {};
825}
826
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800827int32_t getUserActivityEventType(const EventEntry& eventEntry) {
828 switch (eventEntry.type) {
829 case EventEntry::Type::KEY: {
830 return USER_ACTIVITY_EVENT_BUTTON;
831 }
832 case EventEntry::Type::MOTION: {
833 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
834 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
835 return USER_ACTIVITY_EVENT_TOUCH;
836 }
837 return USER_ACTIVITY_EVENT_OTHER;
838 }
839 default: {
840 LOG_ALWAYS_FATAL("%s events are not user activity",
841 ftl::enum_string(eventEntry.type).c_str());
842 }
843 }
844}
845
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000846std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
847 CancelationOptions::Mode mode) {
848 switch (mode) {
849 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
850 return {true, true};
851 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
852 return {true, false};
853 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
854 return {false, true};
855 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
856 return {false, true};
857 }
858}
859
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000860} // namespace
861
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862// --- InputDispatcher ---
863
Prabir Pradhana41d2442023-04-20 21:30:40 +0000864InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000865 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000866
867InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
868 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700869 : mPolicy(policy),
870 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800872 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800873 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700874 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800875 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700876 mDispatchEnabled(false),
877 mDispatchFrozen(false),
878 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100879 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000880 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800881 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000882 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000883 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700884 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800885 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700887 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700888#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700889 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700890#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700891 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000892
893 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000894 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000895 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800896
897 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898}
899
900InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000901 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902
Prabir Pradhancef936d2021-07-21 16:17:52 +0000903 resetKeyRepeatLocked();
904 releasePendingEventLocked();
905 drainInboundQueueLocked();
906 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000908 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700909 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800910 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912}
913
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700914status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700915 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700916 return ALREADY_EXISTS;
917 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700918 mThread = std::make_unique<InputThread>(
919 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
920 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700921}
922
923status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700924 if (mThread && mThread->isCallingThread()) {
925 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700926 return INVALID_OPERATION;
927 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700928 mThread.reset();
929 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700930}
931
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700933 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800935 std::scoped_lock _l(mLock);
936 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 // Run a dispatch loop if there are no pending commands.
939 // The dispatch loop might enqueue commands to run afterwards.
940 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800941 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 }
943
944 // Run all pending commands if there are any.
945 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000946 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700947 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800949
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 // If we are still waiting for ack on some events,
951 // we might have to wake up earlier to check if an app is anr'ing.
952 const nsecs_t nextAnrCheck = processAnrsLocked();
953 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
954
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800955 // We are about to enter an infinitely long sleep, because we have no commands or
956 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700957 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800958 mDispatcherEnteredIdle.notify_all();
959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 } // release lock
961
962 // Wait for callback or timeout or wake. (make sure we round up, not down)
963 nsecs_t currentTime = now();
964 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
965 mLooper->pollOnce(timeoutMillis);
966}
967
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500969 * Raise ANR if there is no focused window.
970 * Before the ANR is raised, do a final state check:
971 * 1. The currently focused application must be the same one we are waiting for.
972 * 2. Ensure we still don't have a focused window.
973 */
974void InputDispatcher::processNoFocusedWindowAnrLocked() {
975 // Check if the application that we are waiting for is still focused.
976 std::shared_ptr<InputApplicationHandle> focusedApplication =
977 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
978 if (focusedApplication == nullptr ||
979 focusedApplication->getApplicationToken() !=
980 mAwaitedFocusedApplication->getApplicationToken()) {
981 // Unexpected because we should have reset the ANR timer when focused application changed
982 ALOGE("Waited for a focused window, but focused application has already changed to %s",
983 focusedApplication->getName().c_str());
984 return; // The focused application has changed.
985 }
986
chaviw98318de2021-05-19 16:45:23 -0500987 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500988 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
989 if (focusedWindowHandle != nullptr) {
990 return; // We now have a focused window. No need for ANR.
991 }
992 onAnrLocked(mAwaitedFocusedApplication);
993}
994
995/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 * Check if any of the connections' wait queues have events that are too old.
997 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
998 * Return the time at which we should wake up next.
999 */
1000nsecs_t InputDispatcher::processAnrsLocked() {
1001 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001002 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001003 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1004 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1005 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001006 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001007 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001008 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001009 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001010 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001011 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001012 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1013 }
1014 }
1015
1016 // Check if any connection ANRs are due
1017 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1018 if (currentTime < nextAnrCheck) { // most likely scenario
1019 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1020 }
1021
1022 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001023 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001024 if (connection == nullptr) {
1025 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1026 return nextAnrCheck;
1027 }
1028 connection->responsive = false;
1029 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001030 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001031 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001032 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033}
1034
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001035std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001036 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001037 if (connection->monitor) {
1038 return mMonitorDispatchingTimeout;
1039 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001040 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001041 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001042 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001043 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001044 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001045}
1046
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001047void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 nsecs_t currentTime = now();
1049
Jeff Browndc5992e2014-04-11 01:27:26 -07001050 // Reset the key repeat timer whenever normal dispatch is suspended while the
1051 // device is in a non-interactive state. This is to ensure that we abort a key
1052 // repeat if the device is just coming out of sleep.
1053 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 resetKeyRepeatLocked();
1055 }
1056
1057 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1058 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001059 if (DEBUG_FOCUS) {
1060 ALOGD("Dispatch frozen. Waiting some more.");
1061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 return;
1063 }
1064
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 // Ready to start a new event.
1066 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001068 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 // Synthesize a key repeat if appropriate.
1070 if (mKeyRepeatState.lastKeyEntry) {
1071 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1072 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1073 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001074 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076 }
1077
1078 // Nothing to do if there is no pending event.
1079 if (!mPendingEvent) {
1080 return;
1081 }
1082 } else {
1083 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001084 mPendingEvent = mInboundQueue.front();
1085 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 traceInboundQueueLengthLocked();
1087 }
1088
1089 // Poke user activity for this event.
1090 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001091 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094
1095 // Now we have an event to dispatch.
1096 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001097 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001101 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
1105
1106 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109
1110 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 const ConfigurationChangedEntry& typedEntry =
1113 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001119 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001120 const DeviceResetEntry& typedEntry =
1121 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 break;
1125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001127 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001128 std::shared_ptr<const FocusEntry> typedEntry =
1129 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001130 dispatchFocusLocked(currentTime, typedEntry);
1131 done = true;
1132 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1133 break;
1134 }
1135
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001136 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001137 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001138 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1139 done = true;
1140 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1141 break;
1142 }
1143
Prabir Pradhan99987712020-11-10 18:43:05 -08001144 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1145 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001146 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001147 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1148 done = true;
1149 break;
1150 }
1151
arthurhungb89ccb02020-12-30 16:19:01 +08001152 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001153 std::shared_ptr<const DragEntry> typedEntry =
1154 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001155 dispatchDragLocked(currentTime, typedEntry);
1156 done = true;
1157 break;
1158 }
1159
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001160 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001161 std::shared_ptr<const KeyEntry> keyEntry =
1162 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001164 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1167 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 break;
1171 }
1172
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001173 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001174 std::shared_ptr<const MotionEntry> motionEntry =
1175 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001176 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001177 // The event is stale. However, only drop stale events if there isn't an ongoing
1178 // gesture. That would allow us to complete the processing of the current stroke.
1179 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1180 if (touchStateIt != mTouchStatesByDisplay.end()) {
1181 const TouchState& touchState = touchStateIt->second;
1182 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1183 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1184 dropReason = DropReason::STALE;
1185 }
1186 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001188 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001189 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1190 // Only drop events that are focus-dispatched.
1191 dropReason = DropReason::BLOCKED;
1192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
Chris Yef59a2f42020-10-16 12:55:26 -07001197
1198 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001199 std::shared_ptr<const SensorEntry> sensorEntry =
1200 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001201
Chris Yef59a2f42020-10-16 12:55:26 -07001202 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1203 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1204 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1205 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1206 dropReason = DropReason::STALE;
1207 }
1208 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1209 done = true;
1210 break;
1211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213
1214 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
Michael Wright3a981722015-06-10 15:26:13 +01001218 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001220 if (mTracer) {
1221 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
1222 mTracer->eventProcessingComplete(*traceTracker);
1223 }
1224 }
1225
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001227 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229}
1230
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001231bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001232 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001233}
1234
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235/**
1236 * Return true if the events preceding this incoming motion event should be dropped
1237 * Return false otherwise (the default behaviour)
1238 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001239bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001241 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001242
1243 // Optimize case where the current application is unresponsive and the user
1244 // decides to touch a window in a different application.
1245 // If the application takes too long to catch up then we drop all events preceding
1246 // the touch into the other window.
1247 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001248 const int32_t displayId = motionEntry.displayId;
1249 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001250 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001251
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001252 sp<WindowInfoHandle> touchedWindowHandle =
1253 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001254 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001255 touchedWindowHandle->getApplicationToken() !=
1256 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001257 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001258 ALOGI("Pruning input queue because user touched a different application while waiting "
1259 "for %s",
1260 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001261 return true;
1262 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001263
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001264 // Alternatively, maybe there's a spy window that could handle this event.
1265 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1266 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1267 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001268 const std::shared_ptr<Connection> connection =
1269 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001270 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001271 // This spy window could take more input. Drop all events preceding this
1272 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001273 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001274 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001275 mAwaitedFocusedApplication->getName().c_str());
1276 return true;
1277 }
1278 }
1279 }
1280
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281 return false;
1282}
1283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001285 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001287 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 traceInboundQueueLengthLocked();
1289
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001291 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001292 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1293 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001296 if (mTracer) {
1297 ensureEventTraced(keyEntry);
1298 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001299
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001300 // If a new up event comes in, and the pending event with same key code has been asked
1301 // to try again later because of the policy. We have to reset the intercept key wake up
1302 // time for it may have been handled in the policy and could be dropped.
1303 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1304 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001305 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001306 if (pendingKey.keyCode == keyEntry.keyCode &&
1307 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001308 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1309 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001310 pendingKey.interceptKeyWakeupTime = 0;
1311 needWake = true;
1312 }
1313 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 break;
1315 }
1316
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001317 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001318 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1319 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001320 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1321 if (mTracer) {
1322 ensureEventTraced(motionEntry);
1323 }
1324 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001326 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001328
1329 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1330 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1331 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1332 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1333 // and some other events have not yet been processed, the dispatcher will wait for
1334 // these events to be processed before dispatching the key event. This is because
1335 // the unprocessed events may cause the focus to change (for example, by launching a
1336 // new window or tapping a different window). To prevent waiting too long, we force
1337 // the key to be sent to the currently focused window when a new tap comes in.
1338 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1339 "just send the pending key event to the currently focused window.");
1340 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001341 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001342 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001343 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001346 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1347 break;
1348 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001349 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001350 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001351 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001352 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001353 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1354 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001355 // nothing to do
1356 break;
1357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 return needWake;
1361}
1362
Prabir Pradhan24047542023-11-02 17:14:59 +00001363void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001364 // Do not store sensor event in recent queue to avoid flooding the queue.
1365 if (entry->type != EventEntry::Type::SENSOR) {
1366 mRecentQueue.push_back(entry);
1367 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001368 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001369 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 }
1371}
1372
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001373sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1374 bool isStylus,
1375 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001377 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001378 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001379 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001380 continue;
1381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001383 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001384 if (!info.isSpy() &&
1385 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001386 return windowHandle;
1387 }
1388 }
1389 return nullptr;
1390}
1391
1392std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001393 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001394 if (touchedWindow == nullptr) {
1395 return {};
1396 }
1397 // Traverse windows from front to back until we encounter the touched window.
1398 std::vector<InputTarget> outsideTargets;
1399 const auto& windowHandles = getWindowHandlesLocked(displayId);
1400 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1401 if (windowHandle == touchedWindow) {
1402 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1403 // below the touched window will not get ACTION_OUTSIDE event.
1404 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001405 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001406
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001407 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001408 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001409 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1410 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001411 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1412 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001413 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001416 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417}
1418
Prabir Pradhand65552b2021-10-07 11:23:50 -07001419std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001420 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001421 // Traverse windows from front to back and gather the touched spy windows.
1422 std::vector<sp<WindowInfoHandle>> spyWindows;
1423 const auto& windowHandles = getWindowHandlesLocked(displayId);
1424 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1425 const WindowInfo& info = *windowHandle->getInfo();
1426
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001427 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001428 continue;
1429 }
1430 if (!info.isSpy()) {
1431 // The first touched non-spy window was found, so return the spy windows touched so far.
1432 return spyWindows;
1433 }
1434 spyWindows.push_back(windowHandle);
1435 }
1436 return spyWindows;
1437}
1438
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 const char* reason;
1441 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001442 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001443 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001444 ALOGD("Dropped event because policy consumed it.");
1445 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 reason = "inbound event was dropped because the policy consumed it";
1447 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001448 case DropReason::DISABLED:
1449 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 ALOGI("Dropped event because input dispatch is disabled.");
1451 }
1452 reason = "inbound event was dropped because input dispatch is disabled";
1453 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001454 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001455 LOG(INFO) << "Dropping because the current application is not responding and the user "
1456 "has started interacting with a different application: "
1457 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001458 reason = "inbound event was dropped because the current application is not responding "
1459 "and the user has started interacting with a different application";
1460 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001461 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 ALOGI("Dropped event because it is stale.");
1463 reason = "inbound event was dropped because it is stale";
1464 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001465 case DropReason::NO_POINTER_CAPTURE:
1466 ALOGI("Dropped event because there is no window with Pointer Capture.");
1467 reason = "inbound event was dropped because there is no window with Pointer Capture";
1468 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001469 case DropReason::NOT_DROPPED: {
1470 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 }
1474
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001475 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001476 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001477 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001478 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1479 options.displayId = keyEntry.displayId;
1480 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001484 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1486 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001487 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001488 options.displayId = motionEntry.displayId;
1489 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 synthesizeCancelationEventsForAllConnectionsLocked(options);
1491 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001492 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1493 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001494 options.displayId = motionEntry.displayId;
1495 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 synthesizeCancelationEventsForAllConnectionsLocked(options);
1497 }
1498 break;
1499 }
Chris Yef59a2f42020-10-16 12:55:26 -07001500 case EventEntry::Type::SENSOR: {
1501 break;
1502 }
arthurhungb89ccb02020-12-30 16:19:01 +08001503 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1504 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001505 break;
1506 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001507 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001508 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001509 case EventEntry::Type::CONFIGURATION_CHANGED:
1510 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001511 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001512 break;
1513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515}
1516
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001518 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
Prabir Pradhancef936d2021-07-21 16:17:52 +00001521bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001522 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 return false;
1524 }
1525
1526 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001527 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001528 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1530 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001531 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533}
1534
Prabir Pradhancef936d2021-07-21 16:17:52 +00001535void InputDispatcher::postCommandLocked(Command&& command) {
1536 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537}
1538
1539void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001540 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001541 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001542 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 releaseInboundEventLocked(entry);
1544 }
1545 traceInboundQueueLengthLocked();
1546}
1547
1548void InputDispatcher::releasePendingEventLocked() {
1549 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001551 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 }
1553}
1554
Prabir Pradhan24047542023-11-02 17:14:59 +00001555void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001556 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001558 if (DEBUG_DISPATCH_CYCLE) {
1559 ALOGD("Injected inbound event was dropped.");
1560 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 }
1563 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001564 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 }
1566 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567}
1568
1569void InputDispatcher::resetKeyRepeatLocked() {
1570 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001571 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573}
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001576 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
Michael Wright2e732952014-09-24 13:26:59 -07001578 uint32_t policyFlags = entry->policyFlags &
1579 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001582 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1583 currentTime, entry->deviceId, entry->source,
1584 entry->displayId, policyFlags, entry->action, entry->flags,
1585 entry->keyCode, entry->scanCode, entry->metaState,
1586 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001589 if (mTracer) {
1590 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1591 }
1592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596}
1597
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001598bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001599 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1601 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
1604 // Reset key repeating in case a keyboard device was added or removed or something.
1605 resetKeyRepeatLocked();
1606
1607 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001608 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1609 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001610 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001611 };
1612 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 return true;
1614}
1615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001616bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1617 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1619 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1620 entry.deviceId);
1621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
liushenxiang42232912021-05-21 20:24:09 +08001623 // Reset key repeating in case a keyboard device was disabled or enabled.
1624 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1625 resetKeyRepeatLocked();
1626 }
1627
Michael Wrightfb04fd52022-11-24 22:31:11 +00001628 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001629 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001631
1632 // Remove all active pointers from this device
1633 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1634 touchState.removeAllPointersForDevice(entry.deviceId);
1635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return true;
1637}
1638
Vishnu Nairad321cd2020-08-20 16:40:21 -07001639void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001640 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001641 if (mPendingEvent != nullptr) {
1642 // Move the pending event to the front of the queue. This will give the chance
1643 // for the pending event to get dispatched to the newly focused window
1644 mInboundQueue.push_front(mPendingEvent);
1645 mPendingEvent = nullptr;
1646 }
1647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648 std::unique_ptr<FocusEntry> focusEntry =
1649 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1650 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001651
1652 // This event should go to the front of the queue, but behind all other focus events
1653 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001654 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1655 [](const std::shared_ptr<const EventEntry>& event) {
1656 return event->type == EventEntry::Type::FOCUS;
1657 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001658
1659 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001660 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001661}
1662
Prabir Pradhan24047542023-11-02 17:14:59 +00001663void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1664 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001665 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1666 if (connection == nullptr) {
1667 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001668 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001669 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001670 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001671 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001672 std::string reason = std::string("reason=").append(entry->reason);
1673 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001674 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001675}
1676
Prabir Pradhan99987712020-11-10 18:43:05 -08001677void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001678 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001679 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001680 dropReason = DropReason::NOT_DROPPED;
1681
Prabir Pradhan99987712020-11-10 18:43:05 -08001682 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001683 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001684
1685 if (entry->pointerCaptureRequest.enable) {
1686 // Enable Pointer Capture.
1687 if (haveWindowWithPointerCapture &&
1688 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001689 // This can happen if pointer capture is disabled and re-enabled before we notify the
1690 // app of the state change, so there is no need to notify the app.
1691 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1692 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001693 }
1694 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001695 // This can happen if a window requests capture and immediately releases capture.
1696 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001697 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001698 return;
1699 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001700 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1701 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1702 return;
1703 }
1704
Vishnu Nairc519ff72021-01-21 08:23:08 -08001705 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001706 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1707 mWindowTokenWithPointerCapture = token;
1708 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001709 // Disable Pointer Capture.
1710 // We do not check if the sequence number matches for requests to disable Pointer Capture
1711 // for two reasons:
1712 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1713 // to disable capture with the same sequence number: one generated by
1714 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1715 // Capture being disabled in InputReader.
1716 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1717 // actual Pointer Capture state that affects events being generated by input devices is
1718 // in InputReader.
1719 if (!haveWindowWithPointerCapture) {
1720 // Pointer capture was already forcefully disabled because of focus change.
1721 dropReason = DropReason::NOT_DROPPED;
1722 return;
1723 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001724 token = mWindowTokenWithPointerCapture;
1725 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001726 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001727 setPointerCaptureLocked(false);
1728 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001729 }
1730
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001731 auto connection = getConnectionLocked(token);
1732 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001733 // Window has gone away, clean up Pointer Capture state.
1734 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001735 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001736 setPointerCaptureLocked(false);
1737 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001738 return;
1739 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001740 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001741 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001742
1743 dropReason = DropReason::NOT_DROPPED;
1744}
1745
Prabir Pradhan24047542023-11-02 17:14:59 +00001746void InputDispatcher::dispatchTouchModeChangeLocked(
1747 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001748 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001749 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001750 if (windowHandles.empty()) {
1751 return;
1752 }
1753 const std::vector<InputTarget> inputTargets =
1754 getInputTargetsFromWindowHandlesLocked(windowHandles);
1755 if (inputTargets.empty()) {
1756 return;
1757 }
1758 entry->dispatchInProgress = true;
1759 dispatchEventLocked(currentTime, entry, inputTargets);
1760}
1761
1762std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1763 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1764 std::vector<InputTarget> inputTargets;
1765 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001766 const sp<IBinder>& token = handle->getToken();
1767 if (token == nullptr) {
1768 continue;
1769 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001770 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1771 if (connection == nullptr) {
1772 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001773 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001774 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001775 }
1776 return inputTargets;
1777}
1778
Prabir Pradhan24047542023-11-02 17:14:59 +00001779bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001780 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 if (!entry->dispatchInProgress) {
1783 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1784 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1785 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1786 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001787 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 // We have seen two identical key downs in a row which indicates that the device
1789 // driver is automatically generating key repeats itself. We take note of the
1790 // repeat here, but we disable our own next key repeat timer since it is clear that
1791 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001792 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1793 // Make sure we don't get key down from a different device. If a different
1794 // device Id has same key pressed down, the new device Id will replace the
1795 // current one to hold the key repeat with repeat count reset.
1796 // In the future when got a KEY_UP on the device id, drop it and do not
1797 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1799 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001800 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 } else {
1802 // Not a repeat. Save key down state in case we do see a repeat later.
1803 resetKeyRepeatLocked();
1804 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1805 }
1806 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001807 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1808 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001809 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001810 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001811 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1812 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001813 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 resetKeyRepeatLocked();
1815 }
1816
1817 if (entry->repeatCount == 1) {
1818 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1819 } else {
1820 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1821 }
1822
1823 entry->dispatchInProgress = true;
1824
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827
1828 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001829 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001831 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 return false; // wait until next wakeup
1833 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001834 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 entry->interceptKeyWakeupTime = 0;
1836 }
1837
1838 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001839 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001841 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001842 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001843
1844 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1845 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1846 };
1847 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001848 // Poke user activity for keys not passed to user
1849 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return false; // wait for the command to run
1851 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001852 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001854 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001855 if (*dropReason == DropReason::NOT_DROPPED) {
1856 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 }
1858 }
1859
1860 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001861 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001862 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1864 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001865 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001866 // Poke user activity for undispatched keys
1867 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return true;
1869 }
1870
1871 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001872 InputEventInjectionResult injectionResult;
1873 sp<WindowInfoHandle> focusedWindow =
1874 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1875 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 return false;
1878 }
1879
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001880 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 return true;
1883 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001884 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1885
1886 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001887 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1888 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001890 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001893 if (mTracer) {
1894 ensureEventTraced(*entry);
1895 for (const auto& target : inputTargets) {
1896 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1897 }
1898 }
1899
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 // Dispatch the key.
1901 dispatchEventLocked(currentTime, entry, inputTargets);
1902 return true;
1903}
1904
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001905void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1907 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1908 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1909 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1910 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1911 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1912 entry.metaState, entry.repeatCount, entry.downTime);
1913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914}
1915
Prabir Pradhancef936d2021-07-21 16:17:52 +00001916void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001917 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001918 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001919 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1920 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1921 "source=0x%x, sensorType=%s",
1922 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001923 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001924 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001925 auto command = [this, entry]() REQUIRES(mLock) {
1926 scoped_unlock unlock(mLock);
1927
1928 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001929 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001930 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001931 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1932 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001933 };
1934 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001935}
1936
1937bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1939 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001940 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001941 }
Chris Yef59a2f42020-10-16 12:55:26 -07001942 { // acquire lock
1943 std::scoped_lock _l(mLock);
1944
1945 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001946 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001947 if (entry->type == EventEntry::Type::SENSOR) {
1948 it = mInboundQueue.erase(it);
1949 releaseInboundEventLocked(entry);
1950 }
1951 }
1952 }
1953 return true;
1954}
1955
Prabir Pradhan24047542023-11-02 17:14:59 +00001956bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1957 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001958 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001961 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 entry->dispatchInProgress = true;
1963
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001964 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966
1967 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001968 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001969 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1971 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 return true;
1973 }
1974
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001975 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
1977 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001978 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 if (isPointerEvent) {
1982 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001983
1984 if (mDragState &&
1985 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1986 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1987 pilferPointersLocked(mDragState->dragWindow->getToken());
1988 }
1989
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001990 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001991 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001992 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1993 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else {
1995 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001996 sp<WindowInfoHandle> focusedWindow =
1997 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1998 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1999 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002000 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2001 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2002 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 return false;
2007 }
2008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002009 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002010 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002011 return true;
2012 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002014 CancelationOptions::Mode mode(
2015 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2016 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002017 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002018 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002019 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 return true;
2021 }
2022
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002023 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002026 if (mTracer) {
2027 ensureEventTraced(*entry);
2028 for (const auto& target : inputTargets) {
2029 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2030 }
2031 }
2032
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 dispatchEventLocked(currentTime, entry, inputTargets);
2035 return true;
2036}
2037
chaviw98318de2021-05-19 16:45:23 -05002038void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002039 bool isExiting, const int32_t rawX,
2040 const int32_t rawY) {
2041 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002042 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002043 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2044 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002045
2046 enqueueInboundEventLocked(std::move(dragEntry));
2047}
2048
Prabir Pradhan24047542023-11-02 17:14:59 +00002049void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2050 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002051 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2052 if (connection == nullptr) {
2053 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002054 }
arthurhungb89ccb02020-12-30 16:19:01 +08002055 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002056 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002057}
2058
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002059void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002060 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002061 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002062 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002063 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002064 "metaState=0x%x, buttonState=0x%x,"
2065 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002066 prefix, entry.eventTime, entry.deviceId,
2067 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2068 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2069 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2070 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002072 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002073 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002074 "x=%f, y=%f, pressure=%f, size=%f, "
2075 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2076 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002077 i, entry.pointerProperties[i].id,
2078 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002079 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2080 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2081 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2082 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2083 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2084 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2085 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2086 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2087 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090}
2091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002092void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002093 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002095 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002096 if (DEBUG_DISPATCH_CYCLE) {
2097 ALOGD("dispatchEventToCurrentInputTargets");
2098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002100 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002101
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2103
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002104 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002106 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002107 std::shared_ptr<Connection> connection = inputTarget.connection;
2108 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
2110}
2111
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002112void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2114 // If the policy decides to close the app, we will get a channel removal event via
2115 // unregisterInputChannel, and will clean up the connection that way. We are already not
2116 // sending new pointers to the connection when it blocked, but focused events will continue to
2117 // pile up.
2118 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002119 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002120 if (connection->status != Connection::Status::NORMAL) {
2121 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002123 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2124 "application not responding");
2125
2126 sp<WindowInfoHandle> windowHandle;
2127 if (!connection->monitor) {
2128 windowHandle = getWindowHandleLocked(connection->getToken());
2129 if (windowHandle == nullptr) {
2130 // The window that is receiving this ANR was removed, so there is no need to generate
2131 // cancellations, because the cancellations would have already been generated when
2132 // the window was removed.
2133 return;
2134 }
2135 }
2136 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137}
2138
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002140 if (DEBUG_FOCUS) {
2141 ALOGD("Resetting ANR timeouts.");
2142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
2144 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002145 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002146 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147}
2148
Tiger Huang721e26f2018-07-24 22:26:19 +08002149/**
2150 * Get the display id that the given event should go to. If this event specifies a valid display id,
2151 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2152 * Focused display is the display that the user most recently interacted with.
2153 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002155 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002157 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002158 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2159 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 break;
2161 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2164 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 break;
2166 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002167 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002168 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002169 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002170 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002171 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002172 case EventEntry::Type::SENSOR:
2173 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002174 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 return ADISPLAY_ID_NONE;
2176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002177 }
2178 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2179}
2180
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2182 const char* focusedWindowName) {
2183 if (mAnrTracker.empty()) {
2184 // already processed all events that we waited for
2185 mKeyIsWaitingForEventsTimeout = std::nullopt;
2186 return false;
2187 }
2188
2189 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2190 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002191 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002192 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002193 std::chrono::duration_cast<std::chrono::nanoseconds>(
2194 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002195 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002196 return true;
2197 }
2198
2199 // We still have pending events, and already started the timer
2200 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2201 return true; // Still waiting
2202 }
2203
2204 // Waited too long, and some connection still hasn't processed all motions
2205 // Just send the key to the focused window
2206 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2207 focusedWindowName);
2208 mKeyIsWaitingForEventsTimeout = std::nullopt;
2209 return false;
2210}
2211
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002212sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002213 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002214 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002215 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216
Tiger Huang721e26f2018-07-24 22:26:19 +08002217 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002218 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002219 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002220 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 // If there is no currently focused window and no focused application
2223 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2225 ALOGI("Dropping %s event because there is no focused window or focused application in "
2226 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002227 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002228 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Vishnu Nair062a8672021-09-03 16:07:44 -07002231 // Drop key events if requested by input feature
2232 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002233 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002234 }
2235
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2237 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2238 // start interacting with another application via touch (app switch). This code can be removed
2239 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2240 // an app is expected to have a focused window.
2241 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2242 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2243 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002244 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2245 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2246 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002248 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 ALOGW("Waiting because no window has focus but %s may eventually add a "
2250 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002251 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002252 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = InputEventInjectionResult::PENDING;
2254 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2256 // Already raised ANR. Drop the event
2257 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002258 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002259 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 } else {
2261 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::PENDING;
2263 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 }
2265 }
2266
2267 // we have a valid, non-null focused window
2268 resetNoFocusedWindowTimeoutLocked();
2269
Prabir Pradhan5735a322022-04-11 17:23:34 +00002270 // Verify targeted injection.
2271 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2272 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002273 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2274 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002277 if (focusedWindowHandle->getInfo()->inputConfig.test(
2278 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002280 outInjectionResult = InputEventInjectionResult::PENDING;
2281 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 }
2283
2284 // If the event is a key event, then we must wait for all previous events to
2285 // complete before delivering it because previous events may have the
2286 // side-effect of transferring focus to a different window and we want to
2287 // ensure that the following keys are sent to the new window.
2288 //
2289 // Suppose the user touches a button in a window then immediately presses "A".
2290 // If the button causes a pop-up window to appear then we want to ensure that
2291 // the "A" key is delivered to the new pop-up window. This is because users
2292 // often anticipate pending UI changes when typing on a keyboard.
2293 // To obtain this behavior, we must serialize key events with respect to all
2294 // prior input events.
2295 if (entry.type == EventEntry::Type::KEY) {
2296 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002297 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002298 outInjectionResult = InputEventInjectionResult::PENDING;
2299 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002303 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2304 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305}
2306
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002307/**
2308 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2309 * that are currently unresponsive.
2310 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002311std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2312 const std::vector<Monitor>& monitors) const {
2313 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002314 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002315 [](const Monitor& monitor) REQUIRES(mLock) {
2316 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002317 if (!connection->responsive) {
2318 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002319 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002320 return false;
2321 }
2322 return true;
2323 });
2324 return responsiveMonitors;
2325}
2326
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002327std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002328 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002329 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002330 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002332 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // For security reasons, we defer updating the touch state until we are sure that
2334 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335 const int32_t displayId = entry.displayId;
2336 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002337 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
2339 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002340 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002342 // Copy current touch state into tempTouchState.
2343 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2344 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002345 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002346 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002347 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2348 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002349 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002350 }
2351
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002352 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002353
2354 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2355 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2356 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002357 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2358 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002359 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002360 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2361 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002362 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2363 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2364 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002365 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002366
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002367 if (newGesture) {
2368 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002369 }
2370
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002371 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2372 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2373 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002376 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002377 if (wasDown) {
2378 // Started hovering, but the device is already down: reject the hover event
2379 LOG(ERROR) << "Got hover event " << entry.getDescription()
2380 << " but the device is already down " << oldState->dump();
2381 outInjectionResult = InputEventInjectionResult::FAILED;
2382 return {};
2383 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002384 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2385 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002386 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002387 }
2388
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2390 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002391 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002392 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002393 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002394 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2395 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002396 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002397 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002398 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002399
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002400 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002401 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002404 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002405 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002408 }
2409
Prabir Pradhan5735a322022-04-11 17:23:34 +00002410 // Verify targeted injection.
2411 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2412 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002413 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002414 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002415 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002416 }
2417
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002419 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2421 // New window supports splitting, but we should never split mouse events.
2422 isSplit = !isFromMouse;
2423 } else if (isSplit) {
2424 // New window does not support splitting but we have already split events.
2425 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002426 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2427 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002428 newTouchedWindowHandle = nullptr;
2429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430 } else {
2431 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002432 // be delivered to a new window which supports split touch. Pointers from a mouse device
2433 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002434 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002435 }
2436
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002437 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002438 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002439 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002440 // Process the foreground window first so that it is the first to receive the event.
2441 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002442 }
2443
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002444 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002445 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2446 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002447 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002448 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002449 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002450 }
2451
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002452 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002453 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 continue;
2455 }
2456
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002457 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002458 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002459 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002460 }
2461
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002462 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002463 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002464
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002465 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2466 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002467 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002468 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002469
2470 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002471 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002472 }
2473 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002474 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002475 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002476 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002477 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002478
2479 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002480
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002481 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002482 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2483 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002484 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002485 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002486 isDownOrPointerDown
2487 ? std::make_optional(entry.eventTime)
2488 : std::nullopt);
2489 // If this is the pointer going down and the touched window has a wallpaper
2490 // then also add the touched wallpaper windows so they are locked in for the
2491 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2492 // SCROLL because the wallpaper engine only supports touch events. We would need to
2493 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2494 // handle these events.
2495 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002496 windowHandle->getInfo()->inputConfig.test(
2497 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2498 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2499 if (wallpaper != nullptr) {
2500 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2501 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002502 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002503 if (isSplit) {
2504 wallpaperFlags |= InputTarget::Flags::SPLIT;
2505 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002506 tempTouchState.addOrUpdateWindow(wallpaper,
2507 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002508 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002509 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002510 }
2511 }
2512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002514
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002515 // If a window is already pilfering some pointers, give it this new pointer as well and
2516 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2517 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002518 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002519 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002520 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002521 // This window is already pilfering some pointers, and this new pointer is also
2522 // going to it. Therefore, take over this pointer and don't give it to anyone
2523 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002524 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002525 }
2526 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002527
2528 // Restrict all pilfered pointers to the pilfering windows.
2529 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 } else {
2531 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2532
2533 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002534 if (!tempTouchState.isDown(entry.deviceId) &&
2535 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002536 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2537 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2538 << " is not down or we previously dropped the pointer down event in "
2539 << "display " << displayId << ": " << entry.getDescription();
2540 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002541 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002542 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002545 // If the pointer is not currently hovering, then ignore the event.
2546 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2547 const int32_t pointerId = entry.pointerProperties[0].id;
2548 if (oldState == nullptr ||
2549 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2550 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2551 "display "
2552 << displayId << ": " << entry.getDescription();
2553 outInjectionResult = InputEventInjectionResult::FAILED;
2554 return {};
2555 }
2556 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2557 }
2558
arthurhung6d4bed92021-03-17 11:59:33 +08002559 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002562 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002563 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002564 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002565 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002566 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002567 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002568 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002569 sp<WindowInfoHandle> newTouchedWindowHandle =
2570 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002571
Prabir Pradhan5735a322022-04-11 17:23:34 +00002572 // Verify targeted injection.
2573 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2574 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002575 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002576 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002577 }
2578
Linnan Libf069a32024-02-29 17:22:59 +00002579 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002580 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002581 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002582 newTouchedWindowHandle = nullptr;
2583 }
2584
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002585 if (newTouchedWindowHandle != nullptr &&
2586 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002587 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002588 oldTouchedWindowHandle->getName().c_str(),
2589 newTouchedWindowHandle->getName().c_str(), displayId);
2590
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002592 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002593 const PointerProperties& pointer = entry.pointerProperties[0];
2594 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002595
2596 const TouchedWindow& touchedWindow =
2597 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002598 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002599 InputTarget::DispatchMode::SLIPPERY_EXIT,
2600 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002601 touchedWindow.getDownTimeInTarget(entry.deviceId),
2602 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603
2604 // Make a slippery entrance into the new window.
2605 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002606 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
2608
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002609 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002610 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002611 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002614 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 }
2616 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002617 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002618 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002619 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002622 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2623 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002624 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002625 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002626
2627 // Check if the wallpaper window should deliver the corresponding event.
2628 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002629 tempTouchState, entry.deviceId, pointer, targets);
2630 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002631 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 }
2633 }
Arthur Hung96483742022-11-15 03:30:48 +00002634
2635 // Update the pointerIds for non-splittable when it received pointer down.
2636 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2637 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002638 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002639 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2640 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002641 // Ignore drag window for it should just track one pointer.
2642 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2643 continue;
2644 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002645 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002646 }
2647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002650 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002651 {
2652 std::vector<TouchedWindow> hoveringWindows =
2653 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2654 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002655 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002656 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2657 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002658 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002659 if (!target) {
2660 continue;
2661 }
2662 // Hardcode to single hovering pointer for now.
2663 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2664 pointerIds.set(entry.pointerProperties[0].id);
2665 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2666 targets.push_back(*target);
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,
3394 mWindowInfosVsyncId);
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 Pradhan2a2da1d2023-11-03 02:16:20 +00003477 // Generate a new MotionEntry with a new eventId using the resolved action and
3478 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003479 resolvedMotion = std::make_shared<
3480 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3481 motionEntry.eventTime, motionEntry.deviceId,
3482 motionEntry.source, motionEntry.displayId,
3483 motionEntry.policyFlags, resolvedAction,
3484 motionEntry.actionButton, resolvedFlags,
3485 motionEntry.metaState, motionEntry.buttonState,
3486 motionEntry.classification, motionEntry.edgeFlags,
3487 motionEntry.xPrecision, motionEntry.yPrecision,
3488 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3489 motionEntry.downTime,
3490 usingProperties.value_or(motionEntry.pointerProperties),
3491 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003492 if (ATRACE_ENABLED()) {
3493 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3494 ") to MotionEvent(id=0x%" PRIx32 ").",
3495 motionEntry.id, resolvedMotion->id);
3496 ATRACE_NAME(message.c_str());
3497 }
3498
3499 // Set the resolved motion entry in the DispatchEntry.
3500 dispatchEntry->eventEntry = resolvedMotion;
3501 eventEntry = resolvedMotion;
3502 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003505 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3506 // devices being active at the same time in the same window, so if a new device is
3507 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003508 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003509 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003510 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003511 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003512 << connection->getInputChannelName() << " with event "
3513 << cancelEvent->getDescription();
3514 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003515 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003516 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003517
3518 // Send these cancel events to the queue before sending the event from the new
3519 // device.
3520 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3521 }
3522
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003523 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003525 LOG(WARNING) << "channel " << connection->getInputChannelName()
3526 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 return; // skip the inconsistent event
3528 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003529 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003530 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003531 // Skip reporting pointer down outside focus to the policy.
3532 break;
3533 }
3534
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003535 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003536 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003537
3538 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003540 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003541 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003542 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3543 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003544 break;
3545 }
Chris Yef59a2f42020-10-16 12:55:26 -07003546 case EventEntry::Type::SENSOR: {
3547 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3548 break;
3549 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003550 case EventEntry::Type::CONFIGURATION_CHANGED:
3551 case EventEntry::Type::DEVICE_RESET: {
3552 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003553 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003554 break;
3555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557
3558 // Remember that we are waiting for this dispatch to complete.
3559 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003560 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 }
3562
3563 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003564 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003565 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003566}
3567
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003568/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003569 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003570 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003571 * The first role is to log input interaction with windows, which helps determine what the user was
3572 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3573 * that user started interacting with launcher window, as well as any other window that received
3574 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3575 * when the set of tokens that received the event changes. It is not logged again as long as the
3576 * user is interacting with the same windows.
3577 *
3578 * The second role is to track input device activity for metrics collection. For each input event,
3579 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3580 * input_interaction logs, the device interaction is reported even when the set of interaction
3581 * tokens do not change.
3582 *
3583 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3584 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003585 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003586void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3587 const std::vector<InputTarget>& targets) {
3588 int32_t deviceId;
3589 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003590 // Skip ACTION_UP events, and all events other than keys and motions
3591 if (entry.type == EventEntry::Type::KEY) {
3592 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3593 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3594 return;
3595 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003596 deviceId = keyEntry.deviceId;
3597 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003598 } else if (entry.type == EventEntry::Type::MOTION) {
3599 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3600 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003601 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3602 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003603 return;
3604 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003605 deviceId = motionEntry.deviceId;
3606 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003607 } else {
3608 return; // Not a key or a motion
3609 }
3610
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003611 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003612 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003613 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003614 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003615 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003616 continue; // Skip windows that receive ACTION_OUTSIDE
3617 }
3618
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003619 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003620 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003621 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003622 if (target.windowHandle) {
3623 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3624 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003625 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003626
3627 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3628 REQUIRES(mLock) {
3629 scoped_unlock unlock(mLock);
3630 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3631 };
3632 postCommandLocked(std::move(command));
3633
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003634 if (newConnectionTokens == mInteractionConnectionTokens) {
3635 return; // no change
3636 }
3637 mInteractionConnectionTokens = newConnectionTokens;
3638
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003639 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003640 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003641 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003642 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003643 std::string message = "Interaction with: " + targetList;
3644 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003645 message += "<none>";
3646 }
3647 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3648}
3649
chaviwfd6d3512019-03-25 13:23:49 -07003650void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003651 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003652 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003653 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3654 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003655 return;
3656 }
3657
Vishnu Nairc519ff72021-01-21 08:23:08 -08003658 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003659 if (focusedToken == token) {
3660 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003661 return;
3662 }
3663
Prabir Pradhancef936d2021-07-21 16:17:52 +00003664 auto command = [this, token]() REQUIRES(mLock) {
3665 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003666 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003667 };
3668 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669}
3670
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003671status_t InputDispatcher::publishMotionEvent(Connection& connection,
3672 DispatchEntry& dispatchEntry) const {
3673 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3674 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3675
3676 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003677 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003678
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003679 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003680 // Set the X and Y offset and X and Y scale depending on the input source.
3681 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003682 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003683 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3684 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003685 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003686 scaledCoords[i] = motionEntry.pointerCoords[i];
3687 // Don't apply window scale here since we don't want scale to affect raw
3688 // coordinates. The scale will be sent back to the client and applied
3689 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003690 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003691 }
3692 usingCoords = scaledCoords;
3693 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003694 }
3695
3696 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3697
3698 // Publish the motion event.
3699 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003700 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3701 motionEntry.source, motionEntry.displayId, std::move(hmac),
3702 motionEntry.action, motionEntry.actionButton,
3703 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3704 motionEntry.metaState, motionEntry.buttonState,
3705 motionEntry.classification, dispatchEntry.transform,
3706 motionEntry.xPrecision, motionEntry.yPrecision,
3707 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3708 dispatchEntry.rawTransform, motionEntry.downTime,
3709 motionEntry.eventTime, motionEntry.getPointerCount(),
3710 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003711}
3712
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003714 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003715 ATRACE_NAME_IF(ATRACE_ENABLED(),
3716 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3717 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003718 if (DEBUG_DISPATCH_CYCLE) {
3719 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003722 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003723 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003725 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003726 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727
3728 // Publish the event.
3729 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003730 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3731 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003732 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003733 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3734 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003735 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003736 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3737 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003740 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003742 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3743 keyEntry.deviceId, keyEntry.source,
3744 keyEntry.displayId, std::move(hmac),
3745 keyEntry.action, dispatchEntry->resolvedFlags,
3746 keyEntry.keyCode, keyEntry.scanCode,
3747 keyEntry.metaState, keyEntry.repeatCount,
3748 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003749 if (mTracer) {
3750 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3751 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003752 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
3754
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003755 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003756 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003757 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3758 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003759 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003760 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003761 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003762 if (mTracer) {
3763 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3764 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003765 break;
3766 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003767
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003768 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003769 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003770 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003772 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003773 break;
3774 }
3775
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003776 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3777 const TouchModeEntry& touchModeEntry =
3778 static_cast<const TouchModeEntry&>(eventEntry);
3779 status = connection->inputPublisher
3780 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3781 touchModeEntry.inTouchMode);
3782
3783 break;
3784 }
3785
Prabir Pradhan99987712020-11-10 18:43:05 -08003786 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3787 const auto& captureEntry =
3788 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3789 status = connection->inputPublisher
3790 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003791 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003792 break;
3793 }
3794
arthurhungb89ccb02020-12-30 16:19:01 +08003795 case EventEntry::Type::DRAG: {
3796 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3797 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3798 dragEntry.id, dragEntry.x,
3799 dragEntry.y,
3800 dragEntry.isExiting);
3801 break;
3802 }
3803
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003804 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003805 case EventEntry::Type::DEVICE_RESET:
3806 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003807 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003808 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003809 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812
3813 // Check the result.
3814 if (status) {
3815 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003816 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 "This is unexpected because the wait queue is empty, so the pipe "
3819 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003820 "event to it, status=%s(%d)",
3821 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3822 status);
Harry Cutts33476232023-01-30 19:57:29 +00003823 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 } else {
3825 // Pipe is full and we are waiting for the app to finish process some events
3826 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003827 if (DEBUG_DISPATCH_CYCLE) {
3828 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3829 "waiting for the application to catch up",
3830 connection->getInputChannelName().c_str());
3831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833 } else {
3834 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003835 "status=%s(%d)",
3836 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3837 status);
Harry Cutts33476232023-01-30 19:57:29 +00003838 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840 return;
3841 }
3842
3843 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003844 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3845 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3846 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003847 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003848 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003849 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003850 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003851 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 }
3853}
3854
chaviw09c8d2d2020-08-24 15:48:26 -07003855std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3856 size_t size;
3857 switch (event.type) {
3858 case VerifiedInputEvent::Type::KEY: {
3859 size = sizeof(VerifiedKeyEvent);
3860 break;
3861 }
3862 case VerifiedInputEvent::Type::MOTION: {
3863 size = sizeof(VerifiedMotionEvent);
3864 break;
3865 }
3866 }
3867 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3868 return mHmacKeyManager.sign(start, size);
3869}
3870
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003871const std::array<uint8_t, 32> InputDispatcher::getSignature(
3872 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003873 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003874 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003875 // Only sign events up and down events as the purely move events
3876 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003877 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003878 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003879
3880 VerifiedMotionEvent verifiedEvent =
3881 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3882 verifiedEvent.actionMasked = actionMasked;
3883 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3884 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003885}
3886
3887const std::array<uint8_t, 32> InputDispatcher::getSignature(
3888 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3889 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3890 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003891 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003892}
3893
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003895 const std::shared_ptr<Connection>& connection,
3896 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003897 if (DEBUG_DISPATCH_CYCLE) {
3898 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3899 connection->getInputChannelName().c_str(), seq, toString(handled));
3900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003902 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 return;
3904 }
3905
3906 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003907 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3908 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3909 };
3910 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911}
3912
3913void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003914 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003916 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003917 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3918 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920
3921 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003922 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003923 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003924 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003925 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
3927 // The connection appears to be unrecoverably broken.
3928 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003929 if (connection->status == Connection::Status::NORMAL) {
3930 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
3932 if (notify) {
3933 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003934 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3935 connection->getInputChannelName().c_str());
3936
3937 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003938 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003939 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003940 };
3941 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 }
3943 }
3944}
3945
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003946void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003947 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003948 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003949 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
3951}
3952
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003953void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003959int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3960 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003961 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003962 if (connection == nullptr) {
3963 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3964 connectionToken.get(), events);
3965 return 0; // remove the callback
3966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003968 bool notify;
3969 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3970 if (!(events & ALOOPER_EVENT_INPUT)) {
3971 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3972 "events=0x%x",
3973 connection->getInputChannelName().c_str(), events);
3974 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003977 nsecs_t currentTime = now();
3978 bool gotOne = false;
3979 status_t status = OK;
3980 for (;;) {
3981 Result<InputPublisher::ConsumerResponse> result =
3982 connection->inputPublisher.receiveConsumerResponse();
3983 if (!result.ok()) {
3984 status = result.error().code();
3985 break;
3986 }
3987
3988 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3989 const InputPublisher::Finished& finish =
3990 std::get<InputPublisher::Finished>(*result);
3991 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3992 finish.consumeTime);
3993 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003994 if (shouldReportMetricsForConnection(*connection)) {
3995 const InputPublisher::Timeline& timeline =
3996 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003997 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3998 connection->getToken(),
3999 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004000 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004001 }
4002 gotOne = true;
4003 }
4004 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004005 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004006 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 return 1;
4008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
4010
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004011 notify = status != DEAD_OBJECT || !connection->monitor;
4012 if (notify) {
4013 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4014 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4015 status);
4016 }
4017 } else {
4018 // Monitor channels are never explicitly unregistered.
4019 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004020 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004021 notify = !connection->monitor && stillHaveWindowHandle;
4022 if (notify) {
4023 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4024 connection->getInputChannelName().c_str(), events);
4025 }
4026 }
4027
4028 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004029 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004030 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031}
4032
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004033void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004035 // Cancel windows (i.e. non-monitors).
4036 // A channel must have at least one window to receive any input. If a window was removed, the
4037 // event streams directed to the window will already have been canceled during window removal.
4038 // So there is no need to generate cancellations for connections without any windows.
4039 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4040 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4041 // through a non-touched window if there are more than one window for an input channel.
4042 if (cancelPointers) {
4043 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4044 if (options.displayId.has_value() && options.displayId != displayId) {
4045 continue;
4046 }
4047 for (const auto& touchedWindow : touchState.windows) {
4048 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4049 }
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004052 // Follow up by generating cancellations for all windows, because we don't explicitly track
4053 // the windows that have an ongoing focus event stream.
4054 if (cancelNonPointers) {
4055 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4056 for (const auto& windowHandle : handles) {
4057 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4058 }
4059 }
4060 }
4061
4062 // Cancel monitors.
4063 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064}
4065
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004067 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004068 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004069 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004070 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4071 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004072 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004073 }
4074}
4075
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004076void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4077 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4078 const std::shared_ptr<Connection>& connection) {
4079 if (windowHandle == nullptr) {
4080 LOG(FATAL) << __func__ << ": Window handle must not be null";
4081 }
4082 if (connection) {
4083 // The connection can be optionally provided to avoid multiple lookups.
4084 if (windowHandle->getToken() != connection->getToken()) {
4085 LOG(FATAL) << __func__
4086 << ": Wrong connection provided for window: " << windowHandle->getName();
4087 }
4088 }
4089
4090 std::shared_ptr<Connection> resolvedConnection =
4091 connection ? connection : getConnectionLocked(windowHandle->getToken());
4092 if (!resolvedConnection) {
4093 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4094 return;
4095 }
4096 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4097}
4098
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004100 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4101 const sp<WindowInfoHandle>& window) {
4102 if (!connection->monitor && window == nullptr) {
4103 LOG(FATAL) << __func__
4104 << ": Cannot send event to non-monitor channel without a window - channel: "
4105 << connection->getInputChannelName();
4106 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004107 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 return;
4109 }
4110
4111 nsecs_t currentTime = now();
4112
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004113 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004114 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004116 if (cancelationEvents.empty()) {
4117 return;
4118 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004119
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4121 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004122 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004123 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004124 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004125 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004126
Arthur Hungb3307ee2021-10-14 10:57:37 +00004127 std::string reason = std::string("reason=").append(options.reason);
4128 android_log_event_list(LOGTAG_INPUT_CANCEL)
4129 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4130
hongzuo liu95785e22022-09-06 02:51:35 +00004131 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004132 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004133 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004134 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004135
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004136 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004137 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004138 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004139
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004140 switch (cancelationEventEntry->type) {
4141 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004142 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004143 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004144 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4145 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004146 } else {
4147 targets.emplace_back(fallbackTarget);
4148 }
4149 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004150 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004152 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004153 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004154 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004155 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004156 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004157 pointerIndex++) {
4158 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4159 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004160 if (mDragState && mDragState->dragWindow->getToken() == token &&
4161 pointerIds.test(mDragState->pointerId)) {
4162 LOG(INFO) << __func__
4163 << ": Canceling drag and drop because the pointers for the drag "
4164 "window are being canceled.";
4165 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4166 mDragState.reset();
4167 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004168 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4169 ftl::Flags<InputTarget::Flags>(), pointerIds,
4170 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004171 } else {
4172 targets.emplace_back(fallbackTarget);
4173 const auto it = mDisplayInfos.find(motionEntry.displayId);
4174 if (it != mDisplayInfos.end()) {
4175 targets.back().displayTransform = it->second.transform;
4176 targets.back().setDefaultPointerTransform(it->second.transform);
4177 }
4178 }
4179 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004180 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004182 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004183 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004184 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4185 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004186 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004187 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004188 break;
4189 }
4190 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004191 case EventEntry::Type::DEVICE_RESET:
4192 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004193 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004194 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004195 break;
4196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 }
4198
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004199 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004200 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004202
hongzuo liu95785e22022-09-06 02:51:35 +00004203 // If the outbound queue was previously empty, start the dispatch cycle going.
4204 if (wasEmpty && !connection->outboundQueue.empty()) {
4205 startDispatchCycleLocked(currentTime, connection);
4206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207}
4208
Svet Ganov5d3bc372020-01-26 23:11:07 -08004209void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004210 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004211 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004212 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004213 return;
4214 }
4215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004216 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004217 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004218
4219 if (downEvents.empty()) {
4220 return;
4221 }
4222
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004224 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4225 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004226 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004227
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004228 const auto [_, touchedWindowState, displayId] =
4229 findTouchStateWindowAndDisplayLocked(connection->getToken());
4230 if (touchedWindowState == nullptr) {
4231 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4232 }
4233 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004234
hongzuo liu95785e22022-09-06 02:51:35 +00004235 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004237 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238 switch (downEventEntry->type) {
4239 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004240 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4241 if (windowHandle != nullptr) {
4242 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004243 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004244 pointerIndex++) {
4245 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4246 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004247 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4248 targetFlags, pointerIds, motionEntry.downTime,
4249 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004250 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004251 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004252 const auto it = mDisplayInfos.find(motionEntry.displayId);
4253 if (it != mDisplayInfos.end()) {
4254 targets.back().displayTransform = it->second.transform;
4255 targets.back().setDefaultPointerTransform(it->second.transform);
4256 }
4257 }
4258 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004259 break;
4260 }
4261
4262 case EventEntry::Type::KEY:
4263 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004264 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004265 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004266 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004267 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004268 case EventEntry::Type::SENSOR:
4269 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004270 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004271 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004272 break;
4273 }
4274 }
4275
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004276 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004277 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004278 }
4279
hongzuo liu95785e22022-09-06 02:51:35 +00004280 // If the outbound queue was previously empty, start the dispatch cycle going.
4281 if (wasEmpty && !connection->outboundQueue.empty()) {
4282 startDispatchCycleLocked(downTime, connection);
4283 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004284}
4285
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004286std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004287 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4288 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004289 const auto& [action, pointerProperties, pointerCoords] =
4290 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4291 /*historySize=*/0, originalMotionEntry.pointerProperties,
4292 originalMotionEntry.pointerCoords, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004294 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4295 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004296 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4297 logDispatchStateLocked();
4298 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4299 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4300 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004301 }
4302
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004303 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004304 ATRACE_NAME_IF(ATRACE_ENABLED(),
4305 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4306 ").",
4307 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004308 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004309 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4310 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004311 originalMotionEntry.deviceId, originalMotionEntry.source,
4312 originalMotionEntry.displayId,
4313 originalMotionEntry.policyFlags, action,
4314 originalMotionEntry.actionButton,
4315 originalMotionEntry.flags, originalMotionEntry.metaState,
4316 originalMotionEntry.buttonState,
4317 originalMotionEntry.classification,
4318 originalMotionEntry.edgeFlags,
4319 originalMotionEntry.xPrecision,
4320 originalMotionEntry.yPrecision,
4321 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004322 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004323 pointerProperties, pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 return splitMotionEntry;
4326}
4327
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004328void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4329 std::scoped_lock _l(mLock);
4330 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4331}
4332
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004333void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004334 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004335 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Antonio Kantekf16f2832021-09-28 04:39:20 +00004338 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004340 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004342 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004343 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004344 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 } // release lock
4346
4347 if (needWake) {
4348 mLooper->wake();
4349 }
4350}
4351
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004352void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004353 ALOGD_IF(debugInboundEventDetails(),
4354 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4355 ", deviceId=%d, source=%s, displayId=%" PRId32
4356 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4357 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004358 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4359 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4360 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004361 Result<void> keyCheck = validateKeyEvent(args.action);
4362 if (!keyCheck.ok()) {
4363 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 return;
4365 }
4366
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367 uint32_t policyFlags = args.policyFlags;
4368 int32_t flags = args.flags;
4369 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004370 // InputDispatcher tracks and generates key repeats on behalf of
4371 // whatever notifies it, so repeatCount should always be set to 0
4372 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4374 policyFlags |= POLICY_FLAG_VIRTUAL;
4375 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 if (policyFlags & POLICY_FLAG_FUNCTION) {
4378 metaState |= AMETA_FUNCTION_ON;
4379 }
4380
4381 policyFlags |= POLICY_FLAG_TRUSTED;
4382
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004383 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004385 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4386 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4387 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388
Michael Wright2b3c3302018-03-02 17:19:13 +00004389 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004390 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004391 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4392 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395
Antonio Kantekf16f2832021-09-28 04:39:20 +00004396 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 { // acquire lock
4398 mLock.lock();
4399
4400 if (shouldSendKeyToInputFilterLocked(args)) {
4401 mLock.unlock();
4402
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004403 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004404 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 return; // event was consumed by the filter
4406 }
4407
4408 mLock.lock();
4409 }
4410
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004411 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004412 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4413 args.deviceId, args.source, args.displayId, policyFlags,
4414 args.action, flags, keyCode, args.scanCode, metaState,
4415 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004416 if (mTracer) {
4417 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004420 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 mLock.unlock();
4422 } // release lock
4423
4424 if (needWake) {
4425 mLooper->wake();
4426 }
4427}
4428
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004429bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 return mInputFilterEnabled;
4431}
4432
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004433void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004434 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004435 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004436 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004437 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004438 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4439 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004440 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4441 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4442 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4443 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4444 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004445 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004446 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4447 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004448 i, args.pointerProperties[i].id,
4449 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4450 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4451 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4452 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4453 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4454 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4455 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4456 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4457 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4458 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004461
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004462 Result<void> motionCheck =
4463 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4464 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004465 if (!motionCheck.ok()) {
4466 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4467 return;
4468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004470 if (DEBUG_VERIFY_EVENTS) {
4471 auto [it, _] =
4472 mVerifiersByDisplay.try_emplace(args.displayId,
4473 StringPrintf("display %" PRId32, args.displayId));
4474 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004475 it->second.processMovement(args.deviceId, args.source, args.action,
4476 args.getPointerCount(), args.pointerProperties.data(),
4477 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004478 if (!result.ok()) {
4479 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4480 }
4481 }
4482
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004485
4486 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004487 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4488 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004489 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4490 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
Antonio Kantekf16f2832021-09-28 04:39:20 +00004494 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 { // acquire lock
4496 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004497 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4498 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4499 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004500 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004501 if (touchStateIt != mTouchStatesByDisplay.end()) {
4502 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004503 if (touchState.hasTouchingPointers(args.deviceId) ||
4504 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004505 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4506 }
4507 }
4508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509
4510 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004511 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004512 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004513 displayTransform = it->second.transform;
4514 }
4515
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 mLock.unlock();
4517
4518 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4520 args.action, args.actionButton, args.flags, args.edgeFlags,
4521 args.metaState, args.buttonState, args.classification,
4522 displayTransform, args.xPrecision, args.yPrecision,
4523 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004524 args.downTime, args.eventTime, args.getPointerCount(),
4525 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
4527 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004528 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 return; // event was consumed by the filter
4530 }
4531
4532 mLock.lock();
4533 }
4534
4535 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004536 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004537 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4538 args.deviceId, args.source, args.displayId,
4539 policyFlags, args.action, args.actionButton,
4540 args.flags, args.metaState, args.buttonState,
4541 args.classification, args.edgeFlags, args.xPrecision,
4542 args.yPrecision, args.xCursorPosition,
4543 args.yCursorPosition, args.downTime,
4544 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004545 if (mTracer) {
4546 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004549 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4550 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004551 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004552 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004553 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4554 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4555 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004556 }
4557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004558 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 mLock.unlock();
4560 } // release lock
4561
4562 if (needWake) {
4563 mLooper->wake();
4564 }
4565}
4566
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004567void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004568 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004569 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4570 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004571 args.id, args.eventTime, args.deviceId, args.source,
4572 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004573 }
Chris Yef59a2f42020-10-16 12:55:26 -07004574
Antonio Kantekf16f2832021-09-28 04:39:20 +00004575 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004576 { // acquire lock
4577 mLock.lock();
4578
4579 // Just enqueue a new sensor event.
4580 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004581 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4582 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4583 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004584
4585 needWake = enqueueInboundEventLocked(std::move(newEntry));
4586 mLock.unlock();
4587 } // release lock
4588
4589 if (needWake) {
4590 mLooper->wake();
4591 }
4592}
4593
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004594void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004595 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004596 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4597 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004598 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004599 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004600}
4601
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004602bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004603 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604}
4605
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004606void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004607 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004608 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4609 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004610 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004615 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616}
4617
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004618void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004619 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004620 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4621 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623
Antonio Kantekf16f2832021-09-28 04:39:20 +00004624 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004626 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004628 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004629 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004630 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004631
4632 for (auto& [_, verifier] : mVerifiersByDisplay) {
4633 verifier.resetDevice(args.deviceId);
4634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 } // release lock
4636
4637 if (needWake) {
4638 mLooper->wake();
4639 }
4640}
4641
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004642void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004643 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004644 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4645 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004646 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004647
Antonio Kantekf16f2832021-09-28 04:39:20 +00004648 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004649 { // acquire lock
4650 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004651 auto entry =
4652 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004653 needWake = enqueueInboundEventLocked(std::move(entry));
4654 } // release lock
4655
4656 if (needWake) {
4657 mLooper->wake();
4658 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004659}
4660
Prabir Pradhan5735a322022-04-11 17:23:34 +00004661InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004662 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004663 InputEventInjectionSync syncMode,
4664 std::chrono::milliseconds timeout,
4665 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004666 Result<void> eventValidation = validateInputEvent(*event);
4667 if (!eventValidation.ok()) {
4668 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4669 return InputEventInjectionResult::FAILED;
4670 }
4671
Prabir Pradhan65613802023-02-22 23:36:58 +00004672 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004673 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4674 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4675 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4676 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004677 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004678 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
Prabir Pradhan5735a322022-04-11 17:23:34 +00004680 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004682 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004683 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4684 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4685 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4686 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4687 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004688 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004689 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004690 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004691 }
4692
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004693 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4694 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4695
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004696 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004698 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004699 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004700 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004701 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004702 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4703 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4704 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004705 int32_t keyCode = incomingKey.getKeyCode();
4706 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004707 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004708 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004709 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4710 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4711 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4714 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004715 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716
4717 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4718 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004719 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4721 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4722 std::to_string(t.duration().count()).c_str());
4723 }
4724 }
4725
4726 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004727 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004728 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4729 incomingKey.getEventTime(), resolvedDeviceId,
4730 incomingKey.getSource(), incomingKey.getDisplayId(),
4731 policyFlags, action, flags, keyCode,
4732 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004733 incomingKey.getRepeatCount(),
4734 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004735 if (mTracer) {
4736 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4737 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004738 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004739 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 }
4741
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004742 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004743 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004744 const bool isPointerEvent =
4745 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4746 // If a pointer event has no displayId specified, inject it to the default display.
4747 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4748 ? ADISPLAY_ID_DEFAULT
4749 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004750 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751
4752 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004753 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004755 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4756 motionEvent.getAction(), eventTime,
4757 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4759 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4760 std::to_string(t.duration().count()).c_str());
4761 }
4762 }
4763
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004764 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4765 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4766 }
4767
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004768 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004769 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004770 const size_t pointerCount = motionEvent.getPointerCount();
4771 const std::vector<PointerProperties>
4772 pointerProperties(motionEvent.getPointerProperties(),
4773 motionEvent.getPointerProperties() + pointerCount);
4774
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004775 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004776 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004777 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4778 *sampleEventTimes, resolvedDeviceId,
4779 motionEvent.getSource(), displayId, policyFlags,
4780 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004781 motionEvent.getActionButton(), flags,
4782 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004783 motionEvent.getButtonState(),
4784 motionEvent.getClassification(),
4785 motionEvent.getEdgeFlags(),
4786 motionEvent.getXPrecision(),
4787 motionEvent.getYPrecision(),
4788 motionEvent.getRawXCursorPosition(),
4789 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004790 motionEvent.getDownTime(), pointerProperties,
4791 std::vector<PointerCoords>(samplePointerCoords,
4792 samplePointerCoords +
4793 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004794 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004795 if (mTracer) {
4796 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4797 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004798 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004799 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004801 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004802 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004803 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4804 resolvedDeviceId, motionEvent.getSource(), displayId,
4805 policyFlags, motionEvent.getAction(),
4806 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004807 motionEvent.getMetaState(), motionEvent.getButtonState(),
4808 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4809 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4810 motionEvent.getRawXCursorPosition(),
4811 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4812 pointerProperties,
4813 std::vector<PointerCoords>(samplePointerCoords,
4814 samplePointerCoords +
4815 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004816 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4817 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004818 if (mTracer) {
4819 nextInjectedEntry->traceTracker =
4820 mTracer->traceInboundEvent(*nextInjectedEntry);
4821 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004822 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 }
4824 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004828 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004829 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004833 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004834 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004835 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004836 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004837 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004838 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 }
4840
4841 mLock.unlock();
4842
4843 if (needWake) {
4844 mLooper->wake();
4845 }
4846
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004849 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004851 if (syncMode == InputEventInjectionSync::NONE) {
4852 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 } else {
4854 for (;;) {
4855 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004856 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 break;
4858 }
4859
4860 nsecs_t remainingTimeout = endTime - now();
4861 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004862 if (DEBUG_INJECTION) {
4863 ALOGD("injectInputEvent - Timed out waiting for injection result "
4864 "to become available.");
4865 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 break;
4868 }
4869
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004873 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4874 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004876 if (DEBUG_INJECTION) {
4877 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4878 injectionState->pendingForegroundDispatches);
4879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 nsecs_t remainingTimeout = endTime - now();
4881 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004882 if (DEBUG_INJECTION) {
4883 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4884 "dispatches to finish.");
4885 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004886 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 break;
4888 }
4889
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004890 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 }
4892 }
4893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 } // release lock
4895
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004896 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004897 LOG(INFO) << "injectInputEvent - Finished with result "
4898 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900
4901 return injectionResult;
4902}
4903
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004904std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004905 std::array<uint8_t, 32> calculatedHmac;
4906 std::unique_ptr<VerifiedInputEvent> result;
4907 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004908 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004909 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4910 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4911 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004912 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004913 break;
4914 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004915 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004916 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4917 VerifiedMotionEvent verifiedMotionEvent =
4918 verifiedMotionEventFromMotionEvent(motionEvent);
4919 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004920 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004921 break;
4922 }
4923 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004924 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004925 return nullptr;
4926 }
4927 }
4928 if (calculatedHmac == INVALID_HMAC) {
4929 return nullptr;
4930 }
tyiu1573a672023-02-21 22:38:32 +00004931 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004932 return nullptr;
4933 }
4934 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004935}
4936
Prabir Pradhan24047542023-11-02 17:14:59 +00004937void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004938 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004939 if (!entry.injectionState) {
4940 // Not an injected event.
4941 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004943
4944 InjectionState& injectionState = *entry.injectionState;
4945 if (DEBUG_INJECTION) {
4946 LOG(INFO) << "Setting input event injection result to "
4947 << ftl::enum_string(injectionResult);
4948 }
4949
4950 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4951 // Log the outcome since the injector did not wait for the injection result.
4952 switch (injectionResult) {
4953 case InputEventInjectionResult::SUCCEEDED:
4954 ALOGV("Asynchronous input event injection succeeded.");
4955 break;
4956 case InputEventInjectionResult::TARGET_MISMATCH:
4957 ALOGV("Asynchronous input event injection target mismatch.");
4958 break;
4959 case InputEventInjectionResult::FAILED:
4960 ALOGW("Asynchronous input event injection failed.");
4961 break;
4962 case InputEventInjectionResult::TIMED_OUT:
4963 ALOGW("Asynchronous input event injection timed out.");
4964 break;
4965 case InputEventInjectionResult::PENDING:
4966 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4967 break;
4968 }
4969 }
4970
4971 injectionState.injectionResult = injectionResult;
4972 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973}
4974
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004975void InputDispatcher::transformMotionEntryForInjectionLocked(
4976 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004977 // Input injection works in the logical display coordinate space, but the input pipeline works
4978 // display space, so we need to transform the injected events accordingly.
4979 const auto it = mDisplayInfos.find(entry.displayId);
4980 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004981 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004982
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004983 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4984 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4985 const vec2 cursor =
4986 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4987 {entry.xCursorPosition, entry.yCursorPosition});
4988 entry.xCursorPosition = cursor.x;
4989 entry.yCursorPosition = cursor.y;
4990 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004991 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004992 entry.pointerCoords[i] =
4993 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4994 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004995 }
4996}
4997
Prabir Pradhan24047542023-11-02 17:14:59 +00004998void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004999 if (entry.injectionState) {
5000 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 }
5002}
5003
Prabir Pradhan24047542023-11-02 17:14:59 +00005004void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005005 if (entry.injectionState) {
5006 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005008 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005009 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 }
5011 }
5012}
5013
chaviw98318de2021-05-19 16:45:23 -05005014const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005015 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005016 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005017 auto it = mWindowHandlesByDisplay.find(displayId);
5018 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005019}
5020
chaviw98318de2021-05-19 16:45:23 -05005021sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005022 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005023 if (windowHandleToken == nullptr) {
5024 return nullptr;
5025 }
5026
Prabir Pradhan16463382023-10-12 23:03:19 +00005027 if (!displayId) {
5028 // Look through all displays.
5029 for (auto& it : mWindowHandlesByDisplay) {
5030 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5031 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5032 if (windowHandle->getToken() == windowHandleToken) {
5033 return windowHandle;
5034 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005037 return nullptr;
5038 }
5039
Prabir Pradhan16463382023-10-12 23:03:19 +00005040 // Only look through the requested display.
5041 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005042 if (windowHandle->getToken() == windowHandleToken) {
5043 return windowHandle;
5044 }
5045 }
5046 return nullptr;
5047}
5048
chaviw98318de2021-05-19 16:45:23 -05005049sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5050 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005051 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005052 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5053 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005054 if (handle->getId() == windowHandle->getId() &&
5055 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005056 if (windowHandle->getInfo()->displayId != it.first) {
5057 ALOGE("Found window %s in display %" PRId32
5058 ", but it should belong to display %" PRId32,
5059 windowHandle->getName().c_str(), it.first,
5060 windowHandle->getInfo()->displayId);
5061 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005062 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
5065 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005066 return nullptr;
5067}
5068
chaviw98318de2021-05-19 16:45:23 -05005069sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005070 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5071 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072}
5073
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005074ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5075 auto displayInfoIt = mDisplayInfos.find(displayId);
5076 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5077 : kIdentityTransform;
5078}
5079
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005080bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5081 const MotionEntry& motionEntry) const {
5082 const WindowInfo& info = *window->getInfo();
5083
5084 // Skip spy window targets that are not valid for targeted injection.
5085 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005086 return false;
5087 }
5088
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005089 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5090 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5091 return false;
5092 }
5093
5094 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5095 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5096 window->getName().c_str());
5097 return false;
5098 }
5099
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005100 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005101 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005102 ALOGW("Not sending touch to %s because there's no corresponding connection",
5103 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005104 return false;
5105 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005106
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005107 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005108 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005109 return false;
5110 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005111
5112 // Drop events that can't be trusted due to occlusion
5113 const auto [x, y] = resolveTouchedPosition(motionEntry);
5114 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5115 if (!isTouchTrustedLocked(occlusionInfo)) {
5116 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005117 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005118 for (const auto& log : occlusionInfo.debugInfo) {
5119 ALOGD("%s", log.c_str());
5120 }
5121 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005122 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5123 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005124 return false;
5125 }
5126
5127 // Drop touch events if requested by input feature
5128 if (shouldDropInput(motionEntry, window)) {
5129 return false;
5130 }
5131
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005132 // Ignore touches if stylus is down anywhere on screen
5133 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5134 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5135 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5136 return false;
5137 }
5138
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005139 return true;
5140}
5141
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005142void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005143 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5144 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005145 // Remove all handles on a display if there are no windows left.
5146 mWindowHandlesByDisplay.erase(displayId);
5147 return;
5148 }
5149
5150 // Since we compare the pointer of input window handles across window updates, we need
5151 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005152 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5153 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5154 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005155 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005156 }
5157
chaviw98318de2021-05-19 16:45:23 -05005158 std::vector<sp<WindowInfoHandle>> newHandles;
5159 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005160 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005161 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005162 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005163 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005164 const bool canReceiveInput =
5165 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5166 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005167 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005168 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005169 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005170 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005172 }
5173
5174 if (info->displayId != displayId) {
5175 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5176 handle->getName().c_str(), displayId, info->displayId);
5177 continue;
5178 }
5179
Robert Carredd13602020-04-13 17:24:34 -07005180 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5181 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005182 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005183 oldHandle->updateFrom(handle);
5184 newHandles.push_back(oldHandle);
5185 } else {
5186 newHandles.push_back(handle);
5187 }
5188 }
5189
5190 // Insert or replace
5191 mWindowHandlesByDisplay[displayId] = newHandles;
5192}
5193
Arthur Hungb92218b2018-08-14 12:00:21 +08005194/**
5195 * Called from InputManagerService, update window handle list by displayId that can receive input.
5196 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5197 * If set an empty list, remove all handles from the specific display.
5198 * For focused handle, check if need to change and send a cancel event to previous one.
5199 * For removed handle, check if need to send a cancel event if already in touch.
5200 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005201void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005202 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005203 if (DEBUG_FOCUS) {
5204 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005205 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005206 windowList += iwh->getName() + " ";
5207 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005208 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210
Prabir Pradhand65552b2021-10-07 11:23:50 -07005211 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005212 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005213 const WindowInfo& info = *window->getInfo();
5214
5215 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005216 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005217 if (noInputWindow && window->getToken() != nullptr) {
5218 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5219 window->getName().c_str());
5220 window->releaseChannel();
5221 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005222
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005223 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005224 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5225 !info.inputConfig.test(
5226 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005227 "%s has feature SPY, but is not a trusted overlay.",
5228 window->getName().c_str());
5229
Prabir Pradhand65552b2021-10-07 11:23:50 -07005230 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005231 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5232 !info.inputConfig.test(
5233 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005234 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5235 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005236 }
5237
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005239 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005240 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241
chaviw98318de2021-05-19 16:45:23 -05005242 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005243
chaviw98318de2021-05-19 16:45:23 -05005244 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005245
Vishnu Nairc519ff72021-01-21 08:23:08 -08005246 std::optional<FocusResolver::FocusChanges> changes =
5247 mFocusResolver.setInputWindows(displayId, windowHandles);
5248 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005249 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005252 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5253 mTouchStatesByDisplay.find(displayId);
5254 if (stateIt != mTouchStatesByDisplay.end()) {
5255 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005256 for (size_t i = 0; i < state.windows.size();) {
5257 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005258 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005259 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5260 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005261 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5262 "touched window was removed");
5263 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5264 // Since we are about to drop the touch, cancel the events for the wallpaper as
5265 // well.
5266 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5267 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5268 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5269 if (const auto& ww = state.getWallpaperWindow(); ww) {
5270 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005273 state.windows.erase(state.windows.begin() + i);
5274 } else {
5275 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277 }
arthurhungb89ccb02020-12-30 16:19:01 +08005278
arthurhung6d4bed92021-03-17 11:59:33 +08005279 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005280 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005281 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005282 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005283 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005284 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5285 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005286 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005287 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005288 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005289
Arthur Hung72d8dc32020-03-28 00:48:39 +00005290 // Release information for windows that are no longer present.
5291 // This ensures that unused input channels are released promptly.
5292 // Otherwise, they might stick around until the window handle is destroyed
5293 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005294 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005295 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005296 if (DEBUG_FOCUS) {
5297 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005298 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005299 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005300 }
chaviw291d88a2019-02-14 10:33:58 -08005301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302}
5303
5304void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005305 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005306 if (DEBUG_FOCUS) {
5307 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5308 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5309 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005310 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005311 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005312 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 } // release lock
5314
5315 // Wake up poll loop since it may need to make new input dispatching choices.
5316 mLooper->wake();
5317}
5318
Vishnu Nair599f1412021-06-21 10:39:58 -07005319void InputDispatcher::setFocusedApplicationLocked(
5320 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5321 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5322 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5323
5324 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5325 return; // This application is already focused. No need to wake up or change anything.
5326 }
5327
5328 // Set the new application handle.
5329 if (inputApplicationHandle != nullptr) {
5330 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5331 } else {
5332 mFocusedApplicationHandlesByDisplay.erase(displayId);
5333 }
5334
5335 // No matter what the old focused application was, stop waiting on it because it is
5336 // no longer focused.
5337 resetNoFocusedWindowTimeoutLocked();
5338}
5339
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005340void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5341 if (interval.count() < 0) {
5342 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5343 }
5344 std::scoped_lock _l(mLock);
5345 mMinTimeBetweenUserActivityPokes = interval;
5346}
5347
Tiger Huang721e26f2018-07-24 22:26:19 +08005348/**
5349 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5350 * the display not specified.
5351 *
5352 * We track any unreleased events for each window. If a window loses the ability to receive the
5353 * released event, we will send a cancel event to it. So when the focused display is changed, we
5354 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5355 * display. The display-specified events won't be affected.
5356 */
5357void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005358 if (DEBUG_FOCUS) {
5359 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5360 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005362 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005363
5364 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005365 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005366 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005367 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005368 const auto windowHandle =
5369 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5370 if (windowHandle == nullptr) {
5371 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005372 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005373 CancelationOptions
5374 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5375 "The display which contains this window no longer has focus.");
5376 options.displayId = ADISPLAY_ID_NONE;
5377 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005378 }
5379 mFocusedDisplayId = displayId;
5380
Chris Ye3c2d6f52020-08-09 10:39:48 -07005381 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005382 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005383 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005384
Vishnu Nairad321cd2020-08-20 16:40:21 -07005385 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005386 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005387 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005388 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005389 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005390 }
5391 }
5392 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005393 } // release lock
5394
5395 // Wake up poll loop since it may need to make new input dispatching choices.
5396 mLooper->wake();
5397}
5398
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005400 if (DEBUG_FOCUS) {
5401 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403
5404 bool changed;
5405 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005406 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407
5408 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5409 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005410 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412
5413 if (mDispatchEnabled && !enabled) {
5414 resetAndDropEverythingLocked("dispatcher is being disabled");
5415 }
5416
5417 mDispatchEnabled = enabled;
5418 mDispatchFrozen = frozen;
5419 changed = true;
5420 } else {
5421 changed = false;
5422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005423 } // release lock
5424
5425 if (changed) {
5426 // Wake up poll loop since it may need to make new input dispatching choices.
5427 mLooper->wake();
5428 }
5429}
5430
5431void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005432 if (DEBUG_FOCUS) {
5433 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
5436 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005437 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438
5439 if (mInputFilterEnabled == enabled) {
5440 return;
5441 }
5442
5443 mInputFilterEnabled = enabled;
5444 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5445 } // release lock
5446
5447 // Wake up poll loop since there might be work to do to drop everything.
5448 mLooper->wake();
5449}
5450
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005451bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005452 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005453 bool needWake = false;
5454 {
5455 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005456 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005457 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005458 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005459 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5460 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005461 mTouchModePerDisplay.count(displayId) == 0
5462 ? "not set"
5463 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5464
Antonio Kantek15beb512022-06-13 22:35:41 +00005465 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5466 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005467 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005468 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005469 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005470 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5471 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005472 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005473 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005474 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005475 return false;
5476 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005477 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005478 mTouchModePerDisplay[displayId] = inTouchMode;
5479 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5480 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005481 needWake = enqueueInboundEventLocked(std::move(entry));
5482 } // release lock
5483
5484 if (needWake) {
5485 mLooper->wake();
5486 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005487 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005488}
5489
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005490bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005491 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5492 if (focusedToken == nullptr) {
5493 return false;
5494 }
5495 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5496 return isWindowOwnedBy(windowHandle, pid, uid);
5497}
5498
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005499bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005500 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5501 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5502 const sp<WindowInfoHandle> windowHandle =
5503 getWindowHandleLocked(connectionToken);
5504 return isWindowOwnedBy(windowHandle, pid, uid);
5505 }) != mInteractionConnectionTokens.end();
5506}
5507
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005508void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5509 if (opacity < 0 || opacity > 1) {
5510 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5511 return;
5512 }
5513
5514 std::scoped_lock lock(mLock);
5515 mMaximumObscuringOpacityForTouch = opacity;
5516}
5517
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005518std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5519InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005520 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5521 for (TouchedWindow& w : state.windows) {
5522 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005523 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005524 }
5525 }
5526 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005527 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005528}
5529
Prabir Pradhan367f3432024-02-13 23:05:58 +00005530bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5531 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005532 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005533 if (DEBUG_FOCUS) {
5534 ALOGD("Trivial transfer to same window.");
5535 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005536 return true;
5537 }
5538
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005540 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541
Arthur Hungabbb9d82021-09-01 14:52:30 +00005542 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005543 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005544
Arthur Hungabbb9d82021-09-01 14:52:30 +00005545 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005546 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 return false;
5548 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005549 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5550 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005551 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5552 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005553 return false;
5554 }
5555 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005556
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005557 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5558 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5559 if (!toWindowHandle) {
5560 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005561 return false;
5562 }
5563
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005564 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005565 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005566 touchedWindow->windowHandle->getName().c_str(),
5567 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 }
5569
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005571 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005572 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005573 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574
Arthur Hungabbb9d82021-09-01 14:52:30 +00005575 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005576 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005577 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005578 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005579 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005580 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005581 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005582 // Transferring touch focus using this API should not effect the focused window.
5583 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005584 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005585 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
Arthur Hungabbb9d82021-09-01 14:52:30 +00005587 // Store the dragging window.
5588 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005589 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005590 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5591 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005592 return false;
5593 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005594 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005595 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005596 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 }
5598
Arthur Hungabbb9d82021-09-01 14:52:30 +00005599 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005600 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5601 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005602 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005603 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005604 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5605 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005606 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005607 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5608 newTargetFlags);
5609
5610 // Check if the wallpaper window should deliver the corresponding event.
5611 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005612 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 } // release lock
5615
5616 // Wake up poll loop since it may need to make new input dispatching choices.
5617 mLooper->wake();
5618 return true;
5619}
5620
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005621/**
5622 * Get the touched foreground window on the given display.
5623 * Return null if there are no windows touched on that display, or if more than one foreground
5624 * window is being touched.
5625 */
5626sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5627 auto stateIt = mTouchStatesByDisplay.find(displayId);
5628 if (stateIt == mTouchStatesByDisplay.end()) {
5629 ALOGI("No touch state on display %" PRId32, displayId);
5630 return nullptr;
5631 }
5632
5633 const TouchState& state = stateIt->second;
5634 sp<WindowInfoHandle> touchedForegroundWindow;
5635 // If multiple foreground windows are touched, return nullptr
5636 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005637 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005638 if (touchedForegroundWindow != nullptr) {
5639 ALOGI("Two or more foreground windows: %s and %s",
5640 touchedForegroundWindow->getName().c_str(),
5641 window.windowHandle->getName().c_str());
5642 return nullptr;
5643 }
5644 touchedForegroundWindow = window.windowHandle;
5645 }
5646 }
5647 return touchedForegroundWindow;
5648}
5649
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005650// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005651bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5652 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005653 sp<IBinder> fromToken;
5654 { // acquire lock
5655 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005656 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005657 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005658 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5659 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005660 return false;
5661 }
5662
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005663 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5664 if (from == nullptr) {
5665 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5666 return false;
5667 }
5668
5669 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005670 } // release lock
5671
Prabir Pradhan367f3432024-02-13 23:05:58 +00005672 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005673}
5674
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005676 if (DEBUG_FOCUS) {
5677 ALOGD("Resetting and dropping all events (%s).", reason);
5678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679
Michael Wrightfb04fd52022-11-24 22:31:11 +00005680 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 synthesizeCancelationEventsForAllConnectionsLocked(options);
5682
5683 resetKeyRepeatLocked();
5684 releasePendingEventLocked();
5685 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005686 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005688 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005689 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690}
5691
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005692void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005693 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 dumpDispatchStateLocked(dump);
5695
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005696 std::istringstream stream(dump);
5697 std::string line;
5698
5699 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005700 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 }
5702}
5703
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005704std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005705 std::string dump;
5706
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005707 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5708 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005709
5710 std::string windowName = "None";
5711 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005712 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005713 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5714 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5715 : "token has capture without window";
5716 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005717 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005718
5719 return dump;
5720}
5721
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005722void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005723 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5724 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5725 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005726 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727
Tiger Huang721e26f2018-07-24 22:26:19 +08005728 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5729 dump += StringPrintf(INDENT "FocusedApplications:\n");
5730 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5731 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005732 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005733 const std::chrono::duration timeout =
5734 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005735 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005736 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005737 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005740 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005742
Vishnu Nairc519ff72021-01-21 08:23:08 -08005743 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005744 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005746 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005747 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005748 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005749 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5750 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005753 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754 }
5755
arthurhung6d4bed92021-03-17 11:59:33 +08005756 if (mDragState) {
5757 dump += StringPrintf(INDENT "DragState:\n");
5758 mDragState->dump(dump, INDENT2);
5759 }
5760
Arthur Hungb92218b2018-08-14 12:00:21 +08005761 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005762 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5763 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5764 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5765 const auto& displayInfo = it->second;
5766 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5767 displayInfo.logicalHeight);
5768 displayInfo.transform.dump(dump, "transform", INDENT4);
5769 } else {
5770 dump += INDENT2 "No DisplayInfo found!\n";
5771 }
5772
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005773 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005774 dump += INDENT2 "Windows:\n";
5775 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005776 dump += StringPrintf(INDENT3 "%zu: %s", i,
5777 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005778 }
5779 } else {
5780 dump += INDENT2 "Windows: <none>\n";
5781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005784 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005787 if (!mGlobalMonitorsByDisplay.empty()) {
5788 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5789 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005790 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005793 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005796 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797
5798 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005799 if (!mRecentQueue.empty()) {
5800 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005801 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005802 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005803 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005804 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005807 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 }
5809
5810 // Dump event currently being dispatched.
5811 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005812 dump += INDENT "PendingEvent:\n";
5813 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005814 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005815 dump += StringPrintf(", age=%" PRId64 "ms\n",
5816 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005818 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 }
5820
5821 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005822 if (!mInboundQueue.empty()) {
5823 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005824 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005825 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005826 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005827 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005830 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832
Prabir Pradhancef936d2021-07-21 16:17:52 +00005833 if (!mCommandQueue.empty()) {
5834 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5835 } else {
5836 dump += INDENT "CommandQueue: <empty>\n";
5837 }
5838
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005840 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005841 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005842 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005843 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005844 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005845 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005846 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005847 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005849 if (!connection->outboundQueue.empty()) {
5850 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5851 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005852 dump += dumpQueue(connection->outboundQueue, currentTime);
5853
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005855 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 }
5857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005858 if (!connection->waitQueue.empty()) {
5859 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5860 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005861 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005863 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005865 std::string inputStateDump = streamableToString(connection->inputState);
5866 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005867 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005868 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 }
5871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005872 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 }
5874
Antonio Kantek15beb512022-06-13 22:35:41 +00005875 if (!mTouchModePerDisplay.empty()) {
5876 dump += INDENT "TouchModePerDisplay:\n";
5877 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5878 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5879 std::to_string(touchMode).c_str());
5880 }
5881 } else {
5882 dump += INDENT "TouchModePerDisplay: <none>\n";
5883 }
5884
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005885 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005886 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5887 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5888 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005889 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005890 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005891 dump += INDENT "InputTracer: ";
5892 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893}
5894
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005895void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005896 const size_t numMonitors = monitors.size();
5897 for (size_t i = 0; i < numMonitors; i++) {
5898 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005899 const std::shared_ptr<Connection>& connection = monitor.connection;
5900 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005901 dump += "\n";
5902 }
5903}
5904
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005905class LooperEventCallback : public LooperCallback {
5906public:
5907 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5908 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5909
5910private:
5911 std::function<int(int events)> mCallback;
5912};
5913
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005914Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005915 if (DEBUG_CHANNEL_CREATION) {
5916 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005919 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005920 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005921 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005922
5923 if (result) {
5924 return base::Error(result) << "Failed to open input channel pair with name " << name;
5925 }
5926
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005928 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005929 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005930 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005931 std::shared_ptr<Connection> connection =
5932 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5933 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005935 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5936 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005937 ALOGE("Created a new connection, but the token %p is already known", token.get());
5938 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005939
5940 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5941 this, std::placeholders::_1, token);
5942
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005943 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005944 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 } // release lock
5946
5947 // Wake the looper because some connections have changed.
5948 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005949 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950}
5951
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005952Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005953 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005954 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005955 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005956 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005957 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005958 if (result) {
5959 return base::Error(result) << "Failed to open input channel pair with name " << name;
5960 }
5961
Michael Wright3dd60e22019-03-27 22:06:44 +00005962 { // acquire lock
5963 std::scoped_lock _l(mLock);
5964
5965 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005966 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5967 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005968 }
5969
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005970 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005971 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005972 std::shared_ptr<Connection> connection =
5973 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5974 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005975
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005976 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5977 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005978 ALOGE("Created a new connection, but the token %p is already known", token.get());
5979 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005980
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005981 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5982 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005983
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005984 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005985
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005986 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005987 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005988 }
Garfield Tan15601662020-09-22 15:32:38 -07005989
Michael Wright3dd60e22019-03-27 22:06:44 +00005990 // Wake the looper because some connections have changed.
5991 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005992 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005993}
5994
Garfield Tan15601662020-09-22 15:32:38 -07005995status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005996 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005997 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998
Harry Cutts33476232023-01-30 19:57:29 +00005999 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000 if (status) {
6001 return status;
6002 }
6003 } // release lock
6004
6005 // Wake the poll loop because removing the connection may have changed the current
6006 // synchronization state.
6007 mLooper->wake();
6008 return OK;
6009}
6010
Garfield Tan15601662020-09-22 15:32:38 -07006011status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6012 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006013 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006014 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006015 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 return BAD_VALUE;
6017 }
6018
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006019 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006020
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006022 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023 }
6024
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006025 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026
6027 nsecs_t currentTime = now();
6028 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6029
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006030 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 return OK;
6032}
6033
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006034void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006035 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6036 auto& [displayId, monitors] = *it;
6037 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006038 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006039 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006040
Michael Wright3dd60e22019-03-27 22:06:44 +00006041 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006042 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006043 } else {
6044 ++it;
6045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 }
6047}
6048
Michael Wright3dd60e22019-03-27 22:06:44 +00006049status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006050 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006051 return pilferPointersLocked(token);
6052}
Michael Wright3dd60e22019-03-27 22:06:44 +00006053
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006054status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006055 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6056 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006057 LOG(WARNING)
6058 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006059 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006060 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006061
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006062 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006063 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006064 LOG(WARNING)
6065 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6066 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006067 return BAD_VALUE;
6068 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006069 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006070 if (deviceIds.empty()) {
6071 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006072 return BAD_VALUE;
6073 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006075 for (const DeviceId deviceId : deviceIds) {
6076 TouchState& state = *statePtr;
6077 TouchedWindow& window = *windowPtr;
6078 // Send cancel events to all the input channels we're stealing from.
6079 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6080 "input channel stole pointer stream");
6081 options.deviceId = deviceId;
6082 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006083 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6084 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006085 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006086
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006087 std::string canceledWindows;
6088 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006089 if (w.windowHandle->getToken() != token) {
6090 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006091 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006092 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006093 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006094 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006095 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006096 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006097 << " is stealing input gesture for device " << deviceId << " from "
6098 << canceledWindows;
6099
6100 // Prevent the gesture from being sent to any other windows.
6101 // This only blocks relevant pointers to be sent to other windows
6102 window.addPilferingPointers(deviceId, pointerIds);
6103
6104 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006105 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006106 return OK;
6107}
6108
Prabir Pradhan99987712020-11-10 18:43:05 -08006109void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6110 { // acquire lock
6111 std::scoped_lock _l(mLock);
6112 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006113 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006114 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6115 windowHandle != nullptr ? windowHandle->getName().c_str()
6116 : "token without window");
6117 }
6118
Vishnu Nairc519ff72021-01-21 08:23:08 -08006119 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006120 if (focusedToken != windowToken) {
6121 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6122 enabled ? "enable" : "disable");
6123 return;
6124 }
6125
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006126 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006127 ALOGW("Ignoring request to %s Pointer Capture: "
6128 "window has %s requested pointer capture.",
6129 enabled ? "enable" : "disable", enabled ? "already" : "not");
6130 return;
6131 }
6132
Christine Franksb768bb42021-11-29 12:11:31 -08006133 if (enabled) {
6134 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6135 mIneligibleDisplaysForPointerCapture.end(),
6136 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6137 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6138 return;
6139 }
6140 }
6141
Prabir Pradhan99987712020-11-10 18:43:05 -08006142 setPointerCaptureLocked(enabled);
6143 } // release lock
6144
6145 // Wake the thread to process command entries.
6146 mLooper->wake();
6147}
6148
Christine Franksb768bb42021-11-29 12:11:31 -08006149void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6150 { // acquire lock
6151 std::scoped_lock _l(mLock);
6152 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6153 if (!isEligible) {
6154 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6155 }
6156 } // release lock
6157}
6158
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006159std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006160 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006161 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006162 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006163 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006164 }
6165 }
6166 }
6167 return std::nullopt;
6168}
6169
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006170std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6171 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006172 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006173 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006174 }
6175
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006176 for (const auto& [token, connection] : mConnectionsByToken) {
6177 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006178 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 }
6180 }
Robert Carr4e670e52018-08-15 13:26:12 -07006181
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006182 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183}
6184
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006185std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006186 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006187 if (connection == nullptr) {
6188 return "<nullptr>";
6189 }
6190 return connection->getInputChannelName();
6191}
6192
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006193void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006194 mAnrTracker.eraseToken(connection->getToken());
6195 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006196}
6197
Prabir Pradhancef936d2021-07-21 16:17:52 +00006198void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006199 const std::shared_ptr<Connection>& connection,
6200 uint32_t seq, bool handled,
6201 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006202 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006203 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006204
6205 { // Start critical section
6206 auto dispatchEntryIt =
6207 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6208 [seq](auto& e) { return e->seq == seq; });
6209 if (dispatchEntryIt == connection->waitQueue.end()) {
6210 return;
6211 }
6212
6213 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6214
6215 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6216 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006217 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006218 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6219 }
6220 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006221 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006222 dispatchEntry.deliveryTime, consumeTime, finishTime);
6223 }
6224
6225 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006226 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6227 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006228 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006229 }
6230 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231
6232 // Dequeue the event and start the next cycle.
6233 // Because the lock might have been released, it is possible that the
6234 // contents of the wait queue to have been drained, so we need to double-check
6235 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006236 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6237 [seq](auto& e) { return e->seq == seq; });
6238 if (entryIt != connection->waitQueue.end()) {
6239 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6240 connection->waitQueue.erase(entryIt);
6241
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006242 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6244 if (!connection->responsive) {
6245 connection->responsive = isConnectionResponsive(*connection);
6246 if (connection->responsive) {
6247 // The connection was unresponsive, and now it's responsive.
6248 processConnectionResponsiveLocked(*connection);
6249 }
6250 }
6251 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006252 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006253 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6254 // Only dispatch fallbacks if there is a window for the connection.
6255 if (windowHandle != nullptr) {
6256 const auto inputTarget =
6257 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6258 dispatchEntry->targetFlags,
6259 fallbackKeyEntry->downTime);
6260 if (inputTarget.has_value()) {
6261 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6262 *inputTarget);
6263 }
6264 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006265 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006266 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267 }
6268
6269 // Start the next dispatch cycle for this connection.
6270 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271}
6272
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6274 const sp<IBinder>& newToken) {
6275 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6276 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006277 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006278 };
6279 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280}
6281
Prabir Pradhancef936d2021-07-21 16:17:52 +00006282void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6283 auto command = [this, token, x, y]() REQUIRES(mLock) {
6284 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006285 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006286 };
6287 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006288}
6289
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006290void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006291 if (connection == nullptr) {
6292 LOG_ALWAYS_FATAL("Caller must check for nullness");
6293 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006294 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6295 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006297 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006298 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006299 return;
6300 }
6301 /**
6302 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6303 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6304 * has changed. This could cause newer entries to time out before the already dispatched
6305 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6306 * processes the events linearly. So providing information about the oldest entry seems to be
6307 * most useful.
6308 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006309 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6310 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006311 std::string reason =
6312 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006313 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006315 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006316 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006317 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006318
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006319 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6320
6321 // Stop waking up for events on this connection, it is already unresponsive
6322 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323}
6324
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006325void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6326 std::string reason =
6327 StringPrintf("%s does not have a focused window", application->getName().c_str());
6328 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006329
Yabin Cui8eb9c552023-06-08 18:05:07 +00006330 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006332 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 };
6334 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006335}
6336
chaviw98318de2021-05-19 16:45:23 -05006337void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006338 const std::string& reason) {
6339 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6340 updateLastAnrStateLocked(windowLabel, reason);
6341}
6342
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006343void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6344 const std::string& reason) {
6345 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346 updateLastAnrStateLocked(windowLabel, reason);
6347}
6348
6349void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6350 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006351 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006352 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 struct tm tm;
6354 localtime_r(&t, &tm);
6355 char timestr[64];
6356 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006357 mLastAnrState.clear();
6358 mLastAnrState += INDENT "ANR:\n";
6359 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006360 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6361 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006362 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006363}
6364
Prabir Pradhancef936d2021-07-21 16:17:52 +00006365void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006366 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367 const KeyEvent event = createKeyEvent(entry);
6368 nsecs_t delay = 0;
6369 { // release lock
6370 scoped_unlock unlock(mLock);
6371 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006372 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006373 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6374 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6375 std::to_string(t.duration().count()).c_str());
6376 }
6377 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378
6379 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006380 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006381 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006382 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006384 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006385 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387}
6388
Prabir Pradhancef936d2021-07-21 16:17:52 +00006389void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006390 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006391 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006392 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006393 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006394 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006395 };
6396 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006397}
6398
Prabir Pradhanedd96402022-02-15 01:46:16 -08006399void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006400 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006401 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006402 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006403 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 };
6405 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006406}
6407
6408/**
6409 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6410 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6411 * command entry to the command queue.
6412 */
6413void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6414 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006415 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006416 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006417 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006418 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006419 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006420 pid = findMonitorPidByTokenLocked(connectionToken);
6421 } else {
6422 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006423 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006424 reason.c_str());
6425 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6426 if (handle != nullptr) {
6427 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006428 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006429 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006430 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006431}
6432
6433/**
6434 * Tell the policy that a connection has become responsive so that it can stop ANR.
6435 */
6436void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006437 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006438 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006439 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006440 pid = findMonitorPidByTokenLocked(connectionToken);
6441 } else {
6442 // The connection is a window
6443 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6444 if (handle != nullptr) {
6445 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006446 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006447 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006448 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006449}
6450
Prabir Pradhan24047542023-11-02 17:14:59 +00006451std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006452 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006453 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006454 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006455 if (!handled) {
6456 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006457 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006458 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006459 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 // Get the fallback key state.
6463 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006464 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006466 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006467 connection->inputState.removeFallbackKey(originalKeyCode);
6468 }
6469
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006470 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471 // If the application handles the original key for which we previously
6472 // generated a fallback or if the window is not a foreground window,
6473 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006474 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006475 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006476 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6477 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6478 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6479 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6480 keyEntry.policyFlags);
6481 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006482 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484
6485 mLock.unlock();
6486
Prabir Pradhana41d2442023-04-20 21:30:40 +00006487 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006488 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6489 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006490 unhandledKeyFallback) {
6491 event = *unhandledKeyFallback;
6492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493
6494 mLock.lock();
6495
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006496 // Cancel the fallback key, but only if we still have a window for the channel.
6497 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006498 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006499 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6500 if (windowHandle != nullptr) {
6501 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6502 "application handled the original non-fallback key "
6503 "or is no longer a foreground target, "
6504 "canceling previously dispatched fallback key");
6505 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006506 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006509 connection->inputState.removeFallbackKey(originalKeyCode);
6510 }
6511 } else {
6512 // If the application did not handle a non-fallback key, first check
6513 // that we are in a good state to perform unhandled key event processing
6514 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006515 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006517 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6518 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6519 "since this is not an initial down. "
6520 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6521 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6522 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006523 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006525
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006526 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6528 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6529 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6530 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6531 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006532 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533
6534 mLock.unlock();
6535
Prabir Pradhana41d2442023-04-20 21:30:40 +00006536 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006537 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6538 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006539 fb) {
6540 fallback = true;
6541 event = *fb;
6542 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006543
6544 mLock.lock();
6545
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006546 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006548 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006549 }
6550
6551 // Latch the fallback keycode for this key on an initial down.
6552 // The fallback keycode cannot change at any other point in the lifecycle.
6553 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006555 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006557 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006559 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006560 }
6561
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006562 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006563
6564 // Cancel the fallback key if the policy decides not to send it anymore.
6565 // We will continue to dispatch the key to the policy but we will no
6566 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006567 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6568 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006569 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6570 if (fallback) {
6571 ALOGD("Unhandled key event: Policy requested to send key %d"
6572 "as a fallback for %d, but on the DOWN it had requested "
6573 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006574 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006575 } else {
6576 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6577 "but on the DOWN it had requested to send %d. "
6578 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006579 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006580 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006582
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006583 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6584 if (windowHandle != nullptr) {
6585 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6586 "canceling fallback, policy no longer desires it");
6587 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006588 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006589 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006590
6591 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006592 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006593 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006594 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006595 }
6596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006598 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6599 {
6600 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006601 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006602 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006603 for (const auto& [key, value] : fallbackKeys) {
6604 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006605 }
6606 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6607 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006609 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610
6611 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006612 // Return the fallback key that we want dispatched to the channel.
6613 std::unique_ptr<KeyEntry> newEntry =
6614 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6615 event.getEventTime(), event.getDeviceId(),
6616 event.getSource(), event.getDisplayId(),
6617 keyEntry.policyFlags, keyEntry.action,
6618 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6619 *fallbackKeyCode, event.getScanCode(),
6620 event.getMetaState(), event.getRepeatCount(),
6621 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006622 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6623 ALOGD("Unhandled key event: Dispatching fallback key. "
6624 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006625 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006626 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006627 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006628 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006629 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6630 ALOGD("Unhandled key event: No fallback key.");
6631 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006632
6633 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006634 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 }
6636 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006637 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006638}
6639
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640void InputDispatcher::traceInboundQueueLengthLocked() {
6641 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006642 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643 }
6644}
6645
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006646void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647 if (ATRACE_ENABLED()) {
6648 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006649 snprintf(counterName, sizeof(counterName), "oq:%s",
6650 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006651 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652 }
6653}
6654
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006655void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006656 if (ATRACE_ENABLED()) {
6657 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006658 snprintf(counterName, sizeof(counterName), "wq:%s",
6659 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006660 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006661 }
6662}
6663
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006664void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006665 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006667 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006668 dumpDispatchStateLocked(dump);
6669
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006670 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006671 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006672 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006673 }
6674}
6675
6676void InputDispatcher::monitor() {
6677 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006678 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006679 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006680 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681}
6682
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006683/**
6684 * Wake up the dispatcher and wait until it processes all events and commands.
6685 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6686 * this method can be safely called from any thread, as long as you've ensured that
6687 * the work you are interested in completing has already been queued.
6688 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006689bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006690 /**
6691 * Timeout should represent the longest possible time that a device might spend processing
6692 * events and commands.
6693 */
6694 constexpr std::chrono::duration TIMEOUT = 100ms;
6695 std::unique_lock lock(mLock);
6696 mLooper->wake();
6697 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6698 return result == std::cv_status::no_timeout;
6699}
6700
Vishnu Naire798b472020-07-23 13:52:21 -07006701/**
6702 * Sets focus to the window identified by the token. This must be called
6703 * after updating any input window handles.
6704 *
6705 * Params:
6706 * request.token - input channel token used to identify the window that should gain focus.
6707 * request.focusedToken - the token that the caller expects currently to be focused. If the
6708 * specified token does not match the currently focused window, this request will be dropped.
6709 * If the specified focused token matches the currently focused window, the call will succeed.
6710 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6711 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6712 * when requesting the focus change. This determines which request gets
6713 * precedence if there is a focus change request from another source such as pointer down.
6714 */
Vishnu Nair958da932020-08-21 17:12:37 -07006715void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6716 { // acquire lock
6717 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006718 std::optional<FocusResolver::FocusChanges> changes =
6719 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6720 if (changes) {
6721 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006722 }
6723 } // release lock
6724 // Wake up poll loop since it may need to make new input dispatching choices.
6725 mLooper->wake();
6726}
6727
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006728void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6729 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006730 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006731 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6732 ? removedFocusedWindowHandle
6733 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6734 if (resolvedWindow == nullptr) {
6735 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006736 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006737 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6738 "focus left window");
6739 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6740 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006741 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006742 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006743 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006744 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006745 }
6746
Prabir Pradhan99987712020-11-10 18:43:05 -08006747 // If a window has pointer capture, then it must have focus. We need to ensure that this
6748 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6749 // If the window loses focus before it loses pointer capture, then the window can be in a state
6750 // where it has pointer capture but not focus, violating the contract. Therefore we must
6751 // dispatch the pointer capture event before the focus event. Since focus events are added to
6752 // the front of the queue (above), we add the pointer capture event to the front of the queue
6753 // after the focus events are added. This ensures the pointer capture event ends up at the
6754 // front.
6755 disablePointerCaptureForcedLocked();
6756
Vishnu Nairc519ff72021-01-21 08:23:08 -08006757 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006758 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006759 }
6760}
Vishnu Nair958da932020-08-21 17:12:37 -07006761
Prabir Pradhan99987712020-11-10 18:43:05 -08006762void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006763 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006764 return;
6765 }
6766
6767 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6768
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006769 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006770 setPointerCaptureLocked(false);
6771 }
6772
6773 if (!mWindowTokenWithPointerCapture) {
6774 // No need to send capture changes because no window has capture.
6775 return;
6776 }
6777
6778 if (mPendingEvent != nullptr) {
6779 // Move the pending event to the front of the queue. This will give the chance
6780 // for the pending event to be dropped if it is a captured event.
6781 mInboundQueue.push_front(mPendingEvent);
6782 mPendingEvent = nullptr;
6783 }
6784
6785 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006786 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006787 mInboundQueue.push_front(std::move(entry));
6788}
6789
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006790void InputDispatcher::setPointerCaptureLocked(bool enable) {
6791 mCurrentPointerCaptureRequest.enable = enable;
6792 mCurrentPointerCaptureRequest.seq++;
6793 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006794 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006795 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006796 };
6797 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006798}
6799
Vishnu Nair599f1412021-06-21 10:39:58 -07006800void InputDispatcher::displayRemoved(int32_t displayId) {
6801 { // acquire lock
6802 std::scoped_lock _l(mLock);
6803 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006804 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006805 setFocusedApplicationLocked(displayId, nullptr);
6806 // Call focus resolver to clean up stale requests. This must be called after input windows
6807 // have been removed for the removed display.
6808 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006809 // Reset pointer capture eligibility, regardless of previous state.
6810 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006811 // Remove the associated touch mode state.
6812 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006813 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006814 } // release lock
6815
6816 // Wake up poll loop since it may need to make new input dispatching choices.
6817 mLooper->wake();
6818}
6819
Patrick Williamsd828f302023-04-28 17:52:08 -05006820void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006821 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6822 {
6823 // acquire lock
6824 std::scoped_lock _l(mLock);
6825 logDispatchStateLocked();
6826 }
6827 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6828 result.error().message().c_str());
6829 };
chaviw15fab6f2021-06-07 14:15:52 -05006830 // The listener sends the windows as a flattened array. Separate the windows by display for
6831 // more convenient parsing.
6832 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006833 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006834 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006835 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006836 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006837
6838 { // acquire lock
6839 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006840
6841 // Ensure that we have an entry created for all existing displays so that if a displayId has
6842 // no windows, we can tell that the windows were removed from the display.
6843 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6844 handlesPerDisplay[displayId];
6845 }
6846
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006847 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006848 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006849 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6850 }
6851
6852 for (const auto& [displayId, handles] : handlesPerDisplay) {
6853 setInputWindowsLocked(handles, displayId);
6854 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006855
6856 if (update.vsyncId < mWindowInfosVsyncId) {
6857 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6858 ", current update vsync id: %" PRId64,
6859 mWindowInfosVsyncId, update.vsyncId);
6860 }
6861 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006862 }
6863 // Wake up poll loop since it may need to make new input dispatching choices.
6864 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006865}
6866
Vishnu Nair062a8672021-09-03 16:07:44 -07006867bool InputDispatcher::shouldDropInput(
6868 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006869 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6870 (windowHandle->getInfo()->inputConfig.test(
6871 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006872 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006873 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6874 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006875 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006876 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006877 windowHandle->getInfo()->displayId);
6878 return true;
6879 }
6880 return false;
6881}
6882
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006883void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006884 const gui::WindowInfosUpdate& update) {
6885 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006886}
6887
Arthur Hungdfd528e2021-12-08 13:23:04 +00006888void InputDispatcher::cancelCurrentTouch() {
6889 {
6890 std::scoped_lock _l(mLock);
6891 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006892 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006893 "cancel current touch");
6894 synthesizeCancelationEventsForAllConnectionsLocked(options);
6895
6896 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006897 }
6898 // Wake up poll loop since there might be work to do.
6899 mLooper->wake();
6900}
6901
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006902void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6903 std::scoped_lock _l(mLock);
6904 mMonitorDispatchingTimeout = timeout;
6905}
6906
Arthur Hungc539dbb2022-12-08 07:45:36 +00006907void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6908 const sp<WindowInfoHandle>& oldWindowHandle,
6909 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006910 TouchState& state, int32_t deviceId,
6911 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006912 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006913 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006914 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6915 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6916 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6917 newWindowHandle->getInfo()->inputConfig.test(
6918 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6919 const sp<WindowInfoHandle> oldWallpaper =
6920 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6921 const sp<WindowInfoHandle> newWallpaper =
6922 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6923 if (oldWallpaper == newWallpaper) {
6924 return;
6925 }
6926
6927 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006928 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006929 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006930 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006931 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006932 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006933 }
6934
6935 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006936 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6937 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006938 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006939 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006940 }
6941}
6942
6943void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6944 ftl::Flags<InputTarget::Flags> newTargetFlags,
6945 const sp<WindowInfoHandle> fromWindowHandle,
6946 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006947 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006948 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006949 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6950 fromWindowHandle->getInfo()->inputConfig.test(
6951 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6952 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6953 toWindowHandle->getInfo()->inputConfig.test(
6954 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6955
6956 const sp<WindowInfoHandle> oldWallpaper =
6957 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6958 const sp<WindowInfoHandle> newWallpaper =
6959 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6960 if (oldWallpaper == newWallpaper) {
6961 return;
6962 }
6963
6964 if (oldWallpaper != nullptr) {
6965 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6966 "transferring touch focus to another window");
6967 state.removeWindowByToken(oldWallpaper->getToken());
6968 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6969 }
6970
6971 if (newWallpaper != nullptr) {
6972 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00006973 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
6974 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006975 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6976 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006977 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006978 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006979 std::shared_ptr<Connection> wallpaperConnection =
6980 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006981 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006982 std::shared_ptr<Connection> toConnection =
6983 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006984 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6985 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6986 wallpaperFlags);
6987 }
6988 }
6989}
6990
6991sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6992 const sp<WindowInfoHandle>& windowHandle) const {
6993 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6994 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6995 bool foundWindow = false;
6996 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6997 if (!foundWindow && otherHandle != windowHandle) {
6998 continue;
6999 }
7000 if (windowHandle == otherHandle) {
7001 foundWindow = true;
7002 continue;
7003 }
7004
7005 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7006 return otherHandle;
7007 }
7008 }
7009 return nullptr;
7010}
7011
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007012void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7013 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007014 std::scoped_lock _l(mLock);
7015
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007016 mConfig.keyRepeatTimeout = timeout.count();
7017 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007018}
7019
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007020bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7021 DeviceId deviceId, int32_t pointerId) {
7022 std::scoped_lock _l(mLock);
7023 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7024 if (touchStateIt == mTouchStatesByDisplay.end()) {
7025 return false;
7026 }
7027 for (const TouchedWindow& window : touchStateIt->second.windows) {
7028 if (window.windowHandle->getToken() == token &&
7029 (window.hasTouchingPointer(deviceId, pointerId) ||
7030 window.hasHoveringPointer(deviceId, pointerId))) {
7031 return true;
7032 }
7033 }
7034 return false;
7035}
7036
Garfield Tane84e6f92019-08-29 17:28:41 -07007037} // namespace android::inputdispatcher