blob: ef7b7805a037f19ca4434cb7076cda5a5350d5b7 [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
Vishnu Nair062a8672021-09-03 16:07:44 -07002579 // Drop touch events if requested by input feature
2580 if (newTouchedWindowHandle != nullptr &&
2581 shouldDropInput(entry, newTouchedWindowHandle)) {
2582 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) {
4289 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
4291 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004292 std::vector<PointerProperties> splitPointerProperties;
4293 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004295 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 uint32_t splitPointerCount = 0;
4297
4298 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004301 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004303 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004305 splitPointerProperties.push_back(pointerProperties);
4306 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 splitPointerCount += 1;
4308 }
4309 }
4310
4311 if (splitPointerCount != pointerIds.count()) {
4312 // This is bad. We are missing some of the pointers that we expected to deliver.
4313 // Most likely this indicates that we received an ACTION_MOVE events that has
4314 // different pointer ids than we expected based on the previous ACTION_DOWN
4315 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4316 // in this way.
4317 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004318 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004319 "a broken sequence of pointer ids from the input device: %s",
4320 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004321 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004324 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004326 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4327 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004328 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004330 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004332 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 if (pointerIds.count() == 1) {
4334 // The first/last pointer went down/up.
4335 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004337 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4338 ? AMOTION_EVENT_ACTION_CANCEL
4339 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 } else {
4341 // A secondary pointer went down/up.
4342 uint32_t splitPointerIndex = 0;
4343 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4344 splitPointerIndex += 1;
4345 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 action = maskedAction |
4347 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 }
4349 } else {
4350 // An unrelated pointer changed.
4351 action = AMOTION_EVENT_ACTION_MOVE;
4352 }
4353 }
4354
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004355 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4356 logDispatchStateLocked();
4357 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4358 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4359 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004360 }
4361
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004362 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004363 ATRACE_NAME_IF(ATRACE_ENABLED(),
4364 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4365 ").",
4366 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004367 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004368 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4369 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004370 originalMotionEntry.deviceId, originalMotionEntry.source,
4371 originalMotionEntry.displayId,
4372 originalMotionEntry.policyFlags, action,
4373 originalMotionEntry.actionButton,
4374 originalMotionEntry.flags, originalMotionEntry.metaState,
4375 originalMotionEntry.buttonState,
4376 originalMotionEntry.classification,
4377 originalMotionEntry.edgeFlags,
4378 originalMotionEntry.xPrecision,
4379 originalMotionEntry.yPrecision,
4380 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004381 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004382 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 return splitMotionEntry;
4385}
4386
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004387void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4388 std::scoped_lock _l(mLock);
4389 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4390}
4391
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004392void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004393 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004394 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Antonio Kantekf16f2832021-09-28 04:39:20 +00004397 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004399 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004401 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004402 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004403 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 } // release lock
4405
4406 if (needWake) {
4407 mLooper->wake();
4408 }
4409}
4410
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004411void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004412 ALOGD_IF(debugInboundEventDetails(),
4413 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4414 ", deviceId=%d, source=%s, displayId=%" PRId32
4415 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4416 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4418 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4419 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004420 Result<void> keyCheck = validateKeyEvent(args.action);
4421 if (!keyCheck.ok()) {
4422 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 return;
4424 }
4425
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004426 uint32_t policyFlags = args.policyFlags;
4427 int32_t flags = args.flags;
4428 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004429 // InputDispatcher tracks and generates key repeats on behalf of
4430 // whatever notifies it, so repeatCount should always be set to 0
4431 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4433 policyFlags |= POLICY_FLAG_VIRTUAL;
4434 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 if (policyFlags & POLICY_FLAG_FUNCTION) {
4437 metaState |= AMETA_FUNCTION_ON;
4438 }
4439
4440 policyFlags |= POLICY_FLAG_TRUSTED;
4441
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004444 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4445 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4446 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
Michael Wright2b3c3302018-03-02 17:19:13 +00004448 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004449 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004450 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4451 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454
Antonio Kantekf16f2832021-09-28 04:39:20 +00004455 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 { // acquire lock
4457 mLock.lock();
4458
4459 if (shouldSendKeyToInputFilterLocked(args)) {
4460 mLock.unlock();
4461
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004462 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004463 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 return; // event was consumed by the filter
4465 }
4466
4467 mLock.lock();
4468 }
4469
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004471 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4472 args.deviceId, args.source, args.displayId, policyFlags,
4473 args.action, flags, keyCode, args.scanCode, metaState,
4474 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004475 if (mTracer) {
4476 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004479 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 mLock.unlock();
4481 } // release lock
4482
4483 if (needWake) {
4484 mLooper->wake();
4485 }
4486}
4487
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 return mInputFilterEnabled;
4490}
4491
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004492void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004493 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004494 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004495 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004496 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004497 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4498 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004499 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4500 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4501 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4502 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4503 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004504 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004505 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4506 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004507 i, args.pointerProperties[i].id,
4508 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4509 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4510 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4511 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4512 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4513 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4514 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4515 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4516 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4517 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004520
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004521 Result<void> motionCheck =
4522 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4523 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004524 if (!motionCheck.ok()) {
4525 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4526 return;
4527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004529 if (DEBUG_VERIFY_EVENTS) {
4530 auto [it, _] =
4531 mVerifiersByDisplay.try_emplace(args.displayId,
4532 StringPrintf("display %" PRId32, args.displayId));
4533 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004534 it->second.processMovement(args.deviceId, args.source, args.action,
4535 args.getPointerCount(), args.pointerProperties.data(),
4536 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004537 if (!result.ok()) {
4538 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4539 }
4540 }
4541
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004542 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004544
4545 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004546 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4547 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004548 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4549 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Antonio Kantekf16f2832021-09-28 04:39:20 +00004553 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 { // acquire lock
4555 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004556 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4557 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4558 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004559 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004560 if (touchStateIt != mTouchStatesByDisplay.end()) {
4561 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004562 if (touchState.hasTouchingPointers(args.deviceId) ||
4563 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004564 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4565 }
4566 }
4567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568
4569 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004570 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004571 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004572 displayTransform = it->second.transform;
4573 }
4574
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 mLock.unlock();
4576
4577 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004578 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4579 args.action, args.actionButton, args.flags, args.edgeFlags,
4580 args.metaState, args.buttonState, args.classification,
4581 displayTransform, args.xPrecision, args.yPrecision,
4582 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004583 args.downTime, args.eventTime, args.getPointerCount(),
4584 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
4586 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004587 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 return; // event was consumed by the filter
4589 }
4590
4591 mLock.lock();
4592 }
4593
4594 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004595 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004596 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4597 args.deviceId, args.source, args.displayId,
4598 policyFlags, args.action, args.actionButton,
4599 args.flags, args.metaState, args.buttonState,
4600 args.classification, args.edgeFlags, args.xPrecision,
4601 args.yPrecision, args.xCursorPosition,
4602 args.yCursorPosition, args.downTime,
4603 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004604 if (mTracer) {
4605 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004608 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4609 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004610 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004612 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4613 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4614 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004615 }
4616
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004617 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 mLock.unlock();
4619 } // release lock
4620
4621 if (needWake) {
4622 mLooper->wake();
4623 }
4624}
4625
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004626void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004627 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004628 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4629 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004630 args.id, args.eventTime, args.deviceId, args.source,
4631 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004632 }
Chris Yef59a2f42020-10-16 12:55:26 -07004633
Antonio Kantekf16f2832021-09-28 04:39:20 +00004634 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004635 { // acquire lock
4636 mLock.lock();
4637
4638 // Just enqueue a new sensor event.
4639 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004640 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4641 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4642 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004643
4644 needWake = enqueueInboundEventLocked(std::move(newEntry));
4645 mLock.unlock();
4646 } // release lock
4647
4648 if (needWake) {
4649 mLooper->wake();
4650 }
4651}
4652
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004653void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004654 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004655 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4656 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004657 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004658 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004659}
4660
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004661bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004662 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663}
4664
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004665void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004666 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004667 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4668 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004669 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004672 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004674 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675}
4676
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004677void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004678 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004679 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4680 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682
Antonio Kantekf16f2832021-09-28 04:39:20 +00004683 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004685 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004687 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004688 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004689 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004690
4691 for (auto& [_, verifier] : mVerifiersByDisplay) {
4692 verifier.resetDevice(args.deviceId);
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 } // release lock
4695
4696 if (needWake) {
4697 mLooper->wake();
4698 }
4699}
4700
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004701void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004702 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004703 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4704 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004705 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004706
Antonio Kantekf16f2832021-09-28 04:39:20 +00004707 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004708 { // acquire lock
4709 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004710 auto entry =
4711 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004712 needWake = enqueueInboundEventLocked(std::move(entry));
4713 } // release lock
4714
4715 if (needWake) {
4716 mLooper->wake();
4717 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004718}
4719
Prabir Pradhan5735a322022-04-11 17:23:34 +00004720InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004721 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004722 InputEventInjectionSync syncMode,
4723 std::chrono::milliseconds timeout,
4724 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004725 Result<void> eventValidation = validateInputEvent(*event);
4726 if (!eventValidation.ok()) {
4727 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4728 return InputEventInjectionResult::FAILED;
4729 }
4730
Prabir Pradhan65613802023-02-22 23:36:58 +00004731 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004732 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4733 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4734 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4735 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004736 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004737 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
Prabir Pradhan5735a322022-04-11 17:23:34 +00004739 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004741 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004742 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4743 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4744 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4745 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4746 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004747 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004748 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004749 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004750 }
4751
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004752 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4753 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4754
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004755 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004757 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004758 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004759 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004760 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004761 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4762 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4763 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004764 int32_t keyCode = incomingKey.getKeyCode();
4765 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004766 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004767 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004768 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4769 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4770 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004772 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4773 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004774 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775
4776 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4777 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004778 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4780 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4781 std::to_string(t.duration().count()).c_str());
4782 }
4783 }
4784
4785 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004786 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004787 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4788 incomingKey.getEventTime(), resolvedDeviceId,
4789 incomingKey.getSource(), incomingKey.getDisplayId(),
4790 policyFlags, action, flags, keyCode,
4791 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004792 incomingKey.getRepeatCount(),
4793 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004794 if (mTracer) {
4795 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4796 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004797 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004801 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004802 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004803 const bool isPointerEvent =
4804 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4805 // If a pointer event has no displayId specified, inject it to the default display.
4806 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4807 ? ADISPLAY_ID_DEFAULT
4808 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004809 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810
4811 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004812 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004813 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004814 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4815 motionEvent.getAction(), eventTime,
4816 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004817 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4818 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4819 std::to_string(t.duration().count()).c_str());
4820 }
4821 }
4822
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004823 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4824 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4825 }
4826
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004828 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004829 const size_t pointerCount = motionEvent.getPointerCount();
4830 const std::vector<PointerProperties>
4831 pointerProperties(motionEvent.getPointerProperties(),
4832 motionEvent.getPointerProperties() + pointerCount);
4833
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004834 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004835 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004836 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4837 *sampleEventTimes, resolvedDeviceId,
4838 motionEvent.getSource(), displayId, policyFlags,
4839 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004840 motionEvent.getActionButton(), flags,
4841 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004842 motionEvent.getButtonState(),
4843 motionEvent.getClassification(),
4844 motionEvent.getEdgeFlags(),
4845 motionEvent.getXPrecision(),
4846 motionEvent.getYPrecision(),
4847 motionEvent.getRawXCursorPosition(),
4848 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004849 motionEvent.getDownTime(), pointerProperties,
4850 std::vector<PointerCoords>(samplePointerCoords,
4851 samplePointerCoords +
4852 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004853 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004854 if (mTracer) {
4855 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004857 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004858 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004859 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004860 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004861 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004862 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4863 resolvedDeviceId, motionEvent.getSource(), displayId,
4864 policyFlags, motionEvent.getAction(),
4865 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004866 motionEvent.getMetaState(), motionEvent.getButtonState(),
4867 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4868 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4869 motionEvent.getRawXCursorPosition(),
4870 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4871 pointerProperties,
4872 std::vector<PointerCoords>(samplePointerCoords,
4873 samplePointerCoords +
4874 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004875 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4876 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004877 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004878 }
4879 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004882 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004883 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004884 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004888 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004889 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004890 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004891 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004892 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004893 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895
4896 mLock.unlock();
4897
4898 if (needWake) {
4899 mLooper->wake();
4900 }
4901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004904 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004906 if (syncMode == InputEventInjectionSync::NONE) {
4907 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 } else {
4909 for (;;) {
4910 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004911 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 break;
4913 }
4914
4915 nsecs_t remainingTimeout = endTime - now();
4916 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004917 if (DEBUG_INJECTION) {
4918 ALOGD("injectInputEvent - Timed out waiting for injection result "
4919 "to become available.");
4920 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004921 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 break;
4923 }
4924
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004925 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004928 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4929 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004931 if (DEBUG_INJECTION) {
4932 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4933 injectionState->pendingForegroundDispatches);
4934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 nsecs_t remainingTimeout = endTime - now();
4936 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004937 if (DEBUG_INJECTION) {
4938 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4939 "dispatches to finish.");
4940 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004941 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 break;
4943 }
4944
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004945 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947 }
4948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 } // release lock
4950
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004951 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004952 LOG(INFO) << "injectInputEvent - Finished with result "
4953 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
4956 return injectionResult;
4957}
4958
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004959std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004960 std::array<uint8_t, 32> calculatedHmac;
4961 std::unique_ptr<VerifiedInputEvent> result;
4962 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004963 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004964 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4965 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4966 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004967 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004968 break;
4969 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004970 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004971 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4972 VerifiedMotionEvent verifiedMotionEvent =
4973 verifiedMotionEventFromMotionEvent(motionEvent);
4974 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004975 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004976 break;
4977 }
4978 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004979 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004980 return nullptr;
4981 }
4982 }
4983 if (calculatedHmac == INVALID_HMAC) {
4984 return nullptr;
4985 }
tyiu1573a672023-02-21 22:38:32 +00004986 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004987 return nullptr;
4988 }
4989 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004990}
4991
Prabir Pradhan24047542023-11-02 17:14:59 +00004992void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004993 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004994 if (!entry.injectionState) {
4995 // Not an injected event.
4996 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004998
4999 InjectionState& injectionState = *entry.injectionState;
5000 if (DEBUG_INJECTION) {
5001 LOG(INFO) << "Setting input event injection result to "
5002 << ftl::enum_string(injectionResult);
5003 }
5004
5005 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
5006 // Log the outcome since the injector did not wait for the injection result.
5007 switch (injectionResult) {
5008 case InputEventInjectionResult::SUCCEEDED:
5009 ALOGV("Asynchronous input event injection succeeded.");
5010 break;
5011 case InputEventInjectionResult::TARGET_MISMATCH:
5012 ALOGV("Asynchronous input event injection target mismatch.");
5013 break;
5014 case InputEventInjectionResult::FAILED:
5015 ALOGW("Asynchronous input event injection failed.");
5016 break;
5017 case InputEventInjectionResult::TIMED_OUT:
5018 ALOGW("Asynchronous input event injection timed out.");
5019 break;
5020 case InputEventInjectionResult::PENDING:
5021 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5022 break;
5023 }
5024 }
5025
5026 injectionState.injectionResult = injectionResult;
5027 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028}
5029
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005030void InputDispatcher::transformMotionEntryForInjectionLocked(
5031 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005032 // Input injection works in the logical display coordinate space, but the input pipeline works
5033 // display space, so we need to transform the injected events accordingly.
5034 const auto it = mDisplayInfos.find(entry.displayId);
5035 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005036 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005037
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005038 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5039 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5040 const vec2 cursor =
5041 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5042 {entry.xCursorPosition, entry.yCursorPosition});
5043 entry.xCursorPosition = cursor.x;
5044 entry.yCursorPosition = cursor.y;
5045 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005046 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005047 entry.pointerCoords[i] =
5048 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5049 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005050 }
5051}
5052
Prabir Pradhan24047542023-11-02 17:14:59 +00005053void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005054 if (entry.injectionState) {
5055 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 }
5057}
5058
Prabir Pradhan24047542023-11-02 17:14:59 +00005059void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005060 if (entry.injectionState) {
5061 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005063 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005064 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 }
5066 }
5067}
5068
chaviw98318de2021-05-19 16:45:23 -05005069const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005070 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005071 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005072 auto it = mWindowHandlesByDisplay.find(displayId);
5073 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005074}
5075
chaviw98318de2021-05-19 16:45:23 -05005076sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005077 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005078 if (windowHandleToken == nullptr) {
5079 return nullptr;
5080 }
5081
Prabir Pradhan16463382023-10-12 23:03:19 +00005082 if (!displayId) {
5083 // Look through all displays.
5084 for (auto& it : mWindowHandlesByDisplay) {
5085 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5086 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5087 if (windowHandle->getToken() == windowHandleToken) {
5088 return windowHandle;
5089 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005092 return nullptr;
5093 }
5094
Prabir Pradhan16463382023-10-12 23:03:19 +00005095 // Only look through the requested display.
5096 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005097 if (windowHandle->getToken() == windowHandleToken) {
5098 return windowHandle;
5099 }
5100 }
5101 return nullptr;
5102}
5103
chaviw98318de2021-05-19 16:45:23 -05005104sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5105 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005106 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005107 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5108 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005109 if (handle->getId() == windowHandle->getId() &&
5110 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005111 if (windowHandle->getInfo()->displayId != it.first) {
5112 ALOGE("Found window %s in display %" PRId32
5113 ", but it should belong to display %" PRId32,
5114 windowHandle->getName().c_str(), it.first,
5115 windowHandle->getInfo()->displayId);
5116 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005117 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005121 return nullptr;
5122}
5123
chaviw98318de2021-05-19 16:45:23 -05005124sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005125 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5126 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127}
5128
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005129ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5130 auto displayInfoIt = mDisplayInfos.find(displayId);
5131 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5132 : kIdentityTransform;
5133}
5134
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005135bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5136 const MotionEntry& motionEntry) const {
5137 const WindowInfo& info = *window->getInfo();
5138
5139 // Skip spy window targets that are not valid for targeted injection.
5140 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 return false;
5142 }
5143
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005144 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5145 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5146 return false;
5147 }
5148
5149 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5150 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5151 window->getName().c_str());
5152 return false;
5153 }
5154
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005155 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005156 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005157 ALOGW("Not sending touch to %s because there's no corresponding connection",
5158 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005159 return false;
5160 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005161
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005162 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005163 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005164 return false;
5165 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005166
5167 // Drop events that can't be trusted due to occlusion
5168 const auto [x, y] = resolveTouchedPosition(motionEntry);
5169 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5170 if (!isTouchTrustedLocked(occlusionInfo)) {
5171 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005172 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005173 for (const auto& log : occlusionInfo.debugInfo) {
5174 ALOGD("%s", log.c_str());
5175 }
5176 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005177 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5178 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005179 return false;
5180 }
5181
5182 // Drop touch events if requested by input feature
5183 if (shouldDropInput(motionEntry, window)) {
5184 return false;
5185 }
5186
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005187 // Ignore touches if stylus is down anywhere on screen
5188 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5189 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5190 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5191 return false;
5192 }
5193
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005194 return true;
5195}
5196
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005197void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005198 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5199 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005200 // Remove all handles on a display if there are no windows left.
5201 mWindowHandlesByDisplay.erase(displayId);
5202 return;
5203 }
5204
5205 // Since we compare the pointer of input window handles across window updates, we need
5206 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005207 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5208 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5209 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005210 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005211 }
5212
chaviw98318de2021-05-19 16:45:23 -05005213 std::vector<sp<WindowInfoHandle>> newHandles;
5214 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005215 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005216 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005217 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005218 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005219 const bool canReceiveInput =
5220 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5221 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005222 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005223 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005224 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005225 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005226 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005227 }
5228
5229 if (info->displayId != displayId) {
5230 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5231 handle->getName().c_str(), displayId, info->displayId);
5232 continue;
5233 }
5234
Robert Carredd13602020-04-13 17:24:34 -07005235 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5236 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005237 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005238 oldHandle->updateFrom(handle);
5239 newHandles.push_back(oldHandle);
5240 } else {
5241 newHandles.push_back(handle);
5242 }
5243 }
5244
5245 // Insert or replace
5246 mWindowHandlesByDisplay[displayId] = newHandles;
5247}
5248
Arthur Hungb92218b2018-08-14 12:00:21 +08005249/**
5250 * Called from InputManagerService, update window handle list by displayId that can receive input.
5251 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5252 * If set an empty list, remove all handles from the specific display.
5253 * For focused handle, check if need to change and send a cancel event to previous one.
5254 * For removed handle, check if need to send a cancel event if already in touch.
5255 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005256void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005257 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005258 if (DEBUG_FOCUS) {
5259 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005260 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005261 windowList += iwh->getName() + " ";
5262 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005263 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265
Prabir Pradhand65552b2021-10-07 11:23:50 -07005266 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005267 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005268 const WindowInfo& info = *window->getInfo();
5269
5270 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005271 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005272 if (noInputWindow && window->getToken() != nullptr) {
5273 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5274 window->getName().c_str());
5275 window->releaseChannel();
5276 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005277
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005278 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005279 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5280 !info.inputConfig.test(
5281 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005282 "%s has feature SPY, but is not a trusted overlay.",
5283 window->getName().c_str());
5284
Prabir Pradhand65552b2021-10-07 11:23:50 -07005285 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005286 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5287 !info.inputConfig.test(
5288 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005289 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5290 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005291 }
5292
Arthur Hung72d8dc32020-03-28 00:48:39 +00005293 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005294 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005295 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296
chaviw98318de2021-05-19 16:45:23 -05005297 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005298
chaviw98318de2021-05-19 16:45:23 -05005299 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005300
Vishnu Nairc519ff72021-01-21 08:23:08 -08005301 std::optional<FocusResolver::FocusChanges> changes =
5302 mFocusResolver.setInputWindows(displayId, windowHandles);
5303 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005304 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005307 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5308 mTouchStatesByDisplay.find(displayId);
5309 if (stateIt != mTouchStatesByDisplay.end()) {
5310 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005311 for (size_t i = 0; i < state.windows.size();) {
5312 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005313 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005314 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5315 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005316 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5317 "touched window was removed");
5318 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5319 // Since we are about to drop the touch, cancel the events for the wallpaper as
5320 // well.
5321 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5322 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5323 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5324 if (const auto& ww = state.getWallpaperWindow(); ww) {
5325 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005328 state.windows.erase(state.windows.begin() + i);
5329 } else {
5330 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 }
5332 }
arthurhungb89ccb02020-12-30 16:19:01 +08005333
arthurhung6d4bed92021-03-17 11:59:33 +08005334 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005335 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005336 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005337 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005338 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005339 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5340 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005341 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005342 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005343 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005344
Arthur Hung72d8dc32020-03-28 00:48:39 +00005345 // Release information for windows that are no longer present.
5346 // This ensures that unused input channels are released promptly.
5347 // Otherwise, they might stick around until the window handle is destroyed
5348 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005349 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005350 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005351 if (DEBUG_FOCUS) {
5352 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005353 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005354 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005355 }
chaviw291d88a2019-02-14 10:33:58 -08005356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357}
5358
5359void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005360 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005361 if (DEBUG_FOCUS) {
5362 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5363 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5364 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005365 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005366 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005367 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 } // release lock
5369
5370 // Wake up poll loop since it may need to make new input dispatching choices.
5371 mLooper->wake();
5372}
5373
Vishnu Nair599f1412021-06-21 10:39:58 -07005374void InputDispatcher::setFocusedApplicationLocked(
5375 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5376 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5377 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5378
5379 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5380 return; // This application is already focused. No need to wake up or change anything.
5381 }
5382
5383 // Set the new application handle.
5384 if (inputApplicationHandle != nullptr) {
5385 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5386 } else {
5387 mFocusedApplicationHandlesByDisplay.erase(displayId);
5388 }
5389
5390 // No matter what the old focused application was, stop waiting on it because it is
5391 // no longer focused.
5392 resetNoFocusedWindowTimeoutLocked();
5393}
5394
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005395void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5396 if (interval.count() < 0) {
5397 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5398 }
5399 std::scoped_lock _l(mLock);
5400 mMinTimeBetweenUserActivityPokes = interval;
5401}
5402
Tiger Huang721e26f2018-07-24 22:26:19 +08005403/**
5404 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5405 * the display not specified.
5406 *
5407 * We track any unreleased events for each window. If a window loses the ability to receive the
5408 * released event, we will send a cancel event to it. So when the focused display is changed, we
5409 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5410 * display. The display-specified events won't be affected.
5411 */
5412void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005413 if (DEBUG_FOCUS) {
5414 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5415 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005417 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005418
5419 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005420 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005421 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005422 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005423 const auto windowHandle =
5424 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5425 if (windowHandle == nullptr) {
5426 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005427 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005428 CancelationOptions
5429 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5430 "The display which contains this window no longer has focus.");
5431 options.displayId = ADISPLAY_ID_NONE;
5432 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005433 }
5434 mFocusedDisplayId = displayId;
5435
Chris Ye3c2d6f52020-08-09 10:39:48 -07005436 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005437 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005438 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005439
Vishnu Nairad321cd2020-08-20 16:40:21 -07005440 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005441 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005442 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005443 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005444 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005445 }
5446 }
5447 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005448 } // release lock
5449
5450 // Wake up poll loop since it may need to make new input dispatching choices.
5451 mLooper->wake();
5452}
5453
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005455 if (DEBUG_FOCUS) {
5456 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
5459 bool changed;
5460 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005461 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462
5463 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5464 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005465 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 }
5467
5468 if (mDispatchEnabled && !enabled) {
5469 resetAndDropEverythingLocked("dispatcher is being disabled");
5470 }
5471
5472 mDispatchEnabled = enabled;
5473 mDispatchFrozen = frozen;
5474 changed = true;
5475 } else {
5476 changed = false;
5477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 } // release lock
5479
5480 if (changed) {
5481 // Wake up poll loop since it may need to make new input dispatching choices.
5482 mLooper->wake();
5483 }
5484}
5485
5486void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005487 if (DEBUG_FOCUS) {
5488 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
5491 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005492 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493
5494 if (mInputFilterEnabled == enabled) {
5495 return;
5496 }
5497
5498 mInputFilterEnabled = enabled;
5499 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5500 } // release lock
5501
5502 // Wake up poll loop since there might be work to do to drop everything.
5503 mLooper->wake();
5504}
5505
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005506bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005507 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005508 bool needWake = false;
5509 {
5510 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005511 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005512 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005513 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005514 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5515 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005516 mTouchModePerDisplay.count(displayId) == 0
5517 ? "not set"
5518 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5519
Antonio Kantek15beb512022-06-13 22:35:41 +00005520 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5521 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005522 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005523 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005524 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005525 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5526 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005527 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005528 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005529 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005530 return false;
5531 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005532 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005533 mTouchModePerDisplay[displayId] = inTouchMode;
5534 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5535 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005536 needWake = enqueueInboundEventLocked(std::move(entry));
5537 } // release lock
5538
5539 if (needWake) {
5540 mLooper->wake();
5541 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005542 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005543}
5544
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005545bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005546 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5547 if (focusedToken == nullptr) {
5548 return false;
5549 }
5550 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5551 return isWindowOwnedBy(windowHandle, pid, uid);
5552}
5553
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005554bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005555 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5556 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5557 const sp<WindowInfoHandle> windowHandle =
5558 getWindowHandleLocked(connectionToken);
5559 return isWindowOwnedBy(windowHandle, pid, uid);
5560 }) != mInteractionConnectionTokens.end();
5561}
5562
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005563void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5564 if (opacity < 0 || opacity > 1) {
5565 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5566 return;
5567 }
5568
5569 std::scoped_lock lock(mLock);
5570 mMaximumObscuringOpacityForTouch = opacity;
5571}
5572
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005573std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5574InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005575 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5576 for (TouchedWindow& w : state.windows) {
5577 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005578 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005579 }
5580 }
5581 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005582 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005583}
5584
Prabir Pradhan367f3432024-02-13 23:05:58 +00005585bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5586 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005587 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005588 if (DEBUG_FOCUS) {
5589 ALOGD("Trivial transfer to same window.");
5590 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005591 return true;
5592 }
5593
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005595 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596
Arthur Hungabbb9d82021-09-01 14:52:30 +00005597 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005598 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005599
Arthur Hungabbb9d82021-09-01 14:52:30 +00005600 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005601 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 return false;
5603 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005604 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5605 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005606 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5607 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005608 return false;
5609 }
5610 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005612 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5613 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5614 if (!toWindowHandle) {
5615 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005616 return false;
5617 }
5618
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005619 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005620 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005621 touchedWindow->windowHandle->getName().c_str(),
5622 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
5624
Arthur Hungabbb9d82021-09-01 14:52:30 +00005625 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005626 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005627 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005628 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629
Arthur Hungabbb9d82021-09-01 14:52:30 +00005630 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005631 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005632 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005633 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005634 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005635 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005636 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005637 // Transferring touch focus using this API should not effect the focused window.
5638 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005639 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005640 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641
Arthur Hungabbb9d82021-09-01 14:52:30 +00005642 // Store the dragging window.
5643 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005644 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005645 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5646 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005647 return false;
5648 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005649 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005650 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005651 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 }
5653
Arthur Hungabbb9d82021-09-01 14:52:30 +00005654 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005655 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5656 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005657 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005658 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005659 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5660 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005661 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005662 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5663 newTargetFlags);
5664
5665 // Check if the wallpaper window should deliver the corresponding event.
5666 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005667 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 } // release lock
5670
5671 // Wake up poll loop since it may need to make new input dispatching choices.
5672 mLooper->wake();
5673 return true;
5674}
5675
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005676/**
5677 * Get the touched foreground window on the given display.
5678 * Return null if there are no windows touched on that display, or if more than one foreground
5679 * window is being touched.
5680 */
5681sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5682 auto stateIt = mTouchStatesByDisplay.find(displayId);
5683 if (stateIt == mTouchStatesByDisplay.end()) {
5684 ALOGI("No touch state on display %" PRId32, displayId);
5685 return nullptr;
5686 }
5687
5688 const TouchState& state = stateIt->second;
5689 sp<WindowInfoHandle> touchedForegroundWindow;
5690 // If multiple foreground windows are touched, return nullptr
5691 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005692 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005693 if (touchedForegroundWindow != nullptr) {
5694 ALOGI("Two or more foreground windows: %s and %s",
5695 touchedForegroundWindow->getName().c_str(),
5696 window.windowHandle->getName().c_str());
5697 return nullptr;
5698 }
5699 touchedForegroundWindow = window.windowHandle;
5700 }
5701 }
5702 return touchedForegroundWindow;
5703}
5704
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005705// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005706bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5707 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005708 sp<IBinder> fromToken;
5709 { // acquire lock
5710 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005711 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005712 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005713 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5714 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005715 return false;
5716 }
5717
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005718 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5719 if (from == nullptr) {
5720 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5721 return false;
5722 }
5723
5724 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005725 } // release lock
5726
Prabir Pradhan367f3432024-02-13 23:05:58 +00005727 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005728}
5729
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005731 if (DEBUG_FOCUS) {
5732 ALOGD("Resetting and dropping all events (%s).", reason);
5733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734
Michael Wrightfb04fd52022-11-24 22:31:11 +00005735 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 synthesizeCancelationEventsForAllConnectionsLocked(options);
5737
5738 resetKeyRepeatLocked();
5739 releasePendingEventLocked();
5740 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005741 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005743 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005744 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745}
5746
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005747void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005748 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 dumpDispatchStateLocked(dump);
5750
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005751 std::istringstream stream(dump);
5752 std::string line;
5753
5754 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005755 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 }
5757}
5758
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005759std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005760 std::string dump;
5761
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005762 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5763 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005764
5765 std::string windowName = "None";
5766 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005767 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005768 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5769 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5770 : "token has capture without window";
5771 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005772 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005773
5774 return dump;
5775}
5776
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005777void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005778 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5779 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5780 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005781 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
Tiger Huang721e26f2018-07-24 22:26:19 +08005783 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5784 dump += StringPrintf(INDENT "FocusedApplications:\n");
5785 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5786 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005787 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005788 const std::chrono::duration timeout =
5789 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005790 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005792 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005795 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005797
Vishnu Nairc519ff72021-01-21 08:23:08 -08005798 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005799 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005801 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005802 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005803 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005804 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5805 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806 }
5807 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005808 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 }
5810
arthurhung6d4bed92021-03-17 11:59:33 +08005811 if (mDragState) {
5812 dump += StringPrintf(INDENT "DragState:\n");
5813 mDragState->dump(dump, INDENT2);
5814 }
5815
Arthur Hungb92218b2018-08-14 12:00:21 +08005816 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005817 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5818 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5819 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5820 const auto& displayInfo = it->second;
5821 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5822 displayInfo.logicalHeight);
5823 displayInfo.transform.dump(dump, "transform", INDENT4);
5824 } else {
5825 dump += INDENT2 "No DisplayInfo found!\n";
5826 }
5827
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005828 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005829 dump += INDENT2 "Windows:\n";
5830 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005831 dump += StringPrintf(INDENT3 "%zu: %s", i,
5832 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005833 }
5834 } else {
5835 dump += INDENT2 "Windows: <none>\n";
5836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005839 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 }
5841
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005842 if (!mGlobalMonitorsByDisplay.empty()) {
5843 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5844 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005845 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005848 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 }
5850
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005851 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852
5853 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005854 if (!mRecentQueue.empty()) {
5855 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005856 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005857 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005858 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005859 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005862 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 }
5864
5865 // Dump event currently being dispatched.
5866 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005867 dump += INDENT "PendingEvent:\n";
5868 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005869 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005870 dump += StringPrintf(", age=%" PRId64 "ms\n",
5871 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005873 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 }
5875
5876 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005877 if (!mInboundQueue.empty()) {
5878 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005879 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005880 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005881 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005882 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 }
5884 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005885 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 }
5887
Prabir Pradhancef936d2021-07-21 16:17:52 +00005888 if (!mCommandQueue.empty()) {
5889 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5890 } else {
5891 dump += INDENT "CommandQueue: <empty>\n";
5892 }
5893
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005894 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005895 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005896 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005897 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005899 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005900 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005901 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005902 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005904 if (!connection->outboundQueue.empty()) {
5905 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5906 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005907 dump += dumpQueue(connection->outboundQueue, currentTime);
5908
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005910 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911 }
5912
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005913 if (!connection->waitQueue.empty()) {
5914 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5915 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005916 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005918 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005920 std::string inputStateDump = streamableToString(connection->inputState);
5921 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005922 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005923 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 }
5926 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005927 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 }
5929
Antonio Kantek15beb512022-06-13 22:35:41 +00005930 if (!mTouchModePerDisplay.empty()) {
5931 dump += INDENT "TouchModePerDisplay:\n";
5932 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5933 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5934 std::to_string(touchMode).c_str());
5935 }
5936 } else {
5937 dump += INDENT "TouchModePerDisplay: <none>\n";
5938 }
5939
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005940 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005941 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5942 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5943 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005944 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005945 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005946 dump += INDENT "InputTracer: ";
5947 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948}
5949
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005950void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005951 const size_t numMonitors = monitors.size();
5952 for (size_t i = 0; i < numMonitors; i++) {
5953 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005954 const std::shared_ptr<Connection>& connection = monitor.connection;
5955 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005956 dump += "\n";
5957 }
5958}
5959
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005960class LooperEventCallback : public LooperCallback {
5961public:
5962 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5963 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5964
5965private:
5966 std::function<int(int events)> mCallback;
5967};
5968
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005969Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005970 if (DEBUG_CHANNEL_CREATION) {
5971 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005974 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005975 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005976 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005977
5978 if (result) {
5979 return base::Error(result) << "Failed to open input channel pair with name " << name;
5980 }
5981
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005983 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005984 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005985 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005986 std::shared_ptr<Connection> connection =
5987 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5988 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005990 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5991 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005992 ALOGE("Created a new connection, but the token %p is already known", token.get());
5993 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005994
5995 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5996 this, std::placeholders::_1, token);
5997
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005998 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005999 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000 } // release lock
6001
6002 // Wake the looper because some connections have changed.
6003 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006004 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005}
6006
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006007Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006008 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006009 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006010 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006011 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006012 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006013 if (result) {
6014 return base::Error(result) << "Failed to open input channel pair with name " << name;
6015 }
6016
Michael Wright3dd60e22019-03-27 22:06:44 +00006017 { // acquire lock
6018 std::scoped_lock _l(mLock);
6019
6020 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07006021 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6022 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006023 }
6024
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006025 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006026 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006027 std::shared_ptr<Connection> connection =
6028 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6029 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006030
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006031 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6032 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006033 ALOGE("Created a new connection, but the token %p is already known", token.get());
6034 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006035
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006036 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6037 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006038
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006039 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006040
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006041 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006042 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006043 }
Garfield Tan15601662020-09-22 15:32:38 -07006044
Michael Wright3dd60e22019-03-27 22:06:44 +00006045 // Wake the looper because some connections have changed.
6046 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006047 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006048}
6049
Garfield Tan15601662020-09-22 15:32:38 -07006050status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006052 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053
Harry Cutts33476232023-01-30 19:57:29 +00006054 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 if (status) {
6056 return status;
6057 }
6058 } // release lock
6059
6060 // Wake the poll loop because removing the connection may have changed the current
6061 // synchronization state.
6062 mLooper->wake();
6063 return OK;
6064}
6065
Garfield Tan15601662020-09-22 15:32:38 -07006066status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6067 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006068 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006069 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006070 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 return BAD_VALUE;
6072 }
6073
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006074 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006075
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006077 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078 }
6079
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006080 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081
6082 nsecs_t currentTime = now();
6083 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6084
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006085 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 return OK;
6087}
6088
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006089void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006090 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6091 auto& [displayId, monitors] = *it;
6092 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006093 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006094 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006095
Michael Wright3dd60e22019-03-27 22:06:44 +00006096 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006097 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006098 } else {
6099 ++it;
6100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 }
6102}
6103
Michael Wright3dd60e22019-03-27 22:06:44 +00006104status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006105 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006106 return pilferPointersLocked(token);
6107}
Michael Wright3dd60e22019-03-27 22:06:44 +00006108
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006109status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006110 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6111 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006112 LOG(WARNING)
6113 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006114 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006115 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006116
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006117 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006118 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006119 LOG(WARNING)
6120 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6121 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006122 return BAD_VALUE;
6123 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006124 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006125 if (deviceIds.empty()) {
6126 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006127 return BAD_VALUE;
6128 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006129
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006130 for (const DeviceId deviceId : deviceIds) {
6131 TouchState& state = *statePtr;
6132 TouchedWindow& window = *windowPtr;
6133 // Send cancel events to all the input channels we're stealing from.
6134 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6135 "input channel stole pointer stream");
6136 options.deviceId = deviceId;
6137 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006138 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6139 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006140 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006141
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006142 std::string canceledWindows;
6143 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006144 if (w.windowHandle->getToken() != token) {
6145 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006146 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006147 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006148 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006149 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006150 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006151 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006152 << " is stealing input gesture for device " << deviceId << " from "
6153 << canceledWindows;
6154
6155 // Prevent the gesture from being sent to any other windows.
6156 // This only blocks relevant pointers to be sent to other windows
6157 window.addPilferingPointers(deviceId, pointerIds);
6158
6159 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006160 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006161 return OK;
6162}
6163
Prabir Pradhan99987712020-11-10 18:43:05 -08006164void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6165 { // acquire lock
6166 std::scoped_lock _l(mLock);
6167 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006168 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006169 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6170 windowHandle != nullptr ? windowHandle->getName().c_str()
6171 : "token without window");
6172 }
6173
Vishnu Nairc519ff72021-01-21 08:23:08 -08006174 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006175 if (focusedToken != windowToken) {
6176 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6177 enabled ? "enable" : "disable");
6178 return;
6179 }
6180
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006181 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006182 ALOGW("Ignoring request to %s Pointer Capture: "
6183 "window has %s requested pointer capture.",
6184 enabled ? "enable" : "disable", enabled ? "already" : "not");
6185 return;
6186 }
6187
Christine Franksb768bb42021-11-29 12:11:31 -08006188 if (enabled) {
6189 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6190 mIneligibleDisplaysForPointerCapture.end(),
6191 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6192 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6193 return;
6194 }
6195 }
6196
Prabir Pradhan99987712020-11-10 18:43:05 -08006197 setPointerCaptureLocked(enabled);
6198 } // release lock
6199
6200 // Wake the thread to process command entries.
6201 mLooper->wake();
6202}
6203
Christine Franksb768bb42021-11-29 12:11:31 -08006204void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6205 { // acquire lock
6206 std::scoped_lock _l(mLock);
6207 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6208 if (!isEligible) {
6209 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6210 }
6211 } // release lock
6212}
6213
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006214std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006215 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006216 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006217 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006218 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006219 }
6220 }
6221 }
6222 return std::nullopt;
6223}
6224
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006225std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6226 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006227 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006228 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006229 }
6230
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006231 for (const auto& [token, connection] : mConnectionsByToken) {
6232 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006233 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235 }
Robert Carr4e670e52018-08-15 13:26:12 -07006236
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006237 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238}
6239
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006240std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006241 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006242 if (connection == nullptr) {
6243 return "<nullptr>";
6244 }
6245 return connection->getInputChannelName();
6246}
6247
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006248void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006249 mAnrTracker.eraseToken(connection->getToken());
6250 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006251}
6252
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006254 const std::shared_ptr<Connection>& connection,
6255 uint32_t seq, bool handled,
6256 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006257 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006258 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006259
6260 { // Start critical section
6261 auto dispatchEntryIt =
6262 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6263 [seq](auto& e) { return e->seq == seq; });
6264 if (dispatchEntryIt == connection->waitQueue.end()) {
6265 return;
6266 }
6267
6268 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6269
6270 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6271 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006272 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006273 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6274 }
6275 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006276 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006277 dispatchEntry.deliveryTime, consumeTime, finishTime);
6278 }
6279
6280 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006281 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6282 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006283 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006284 }
6285 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006286
6287 // Dequeue the event and start the next cycle.
6288 // Because the lock might have been released, it is possible that the
6289 // contents of the wait queue to have been drained, so we need to double-check
6290 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006291 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6292 [seq](auto& e) { return e->seq == seq; });
6293 if (entryIt != connection->waitQueue.end()) {
6294 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6295 connection->waitQueue.erase(entryIt);
6296
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006297 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6299 if (!connection->responsive) {
6300 connection->responsive = isConnectionResponsive(*connection);
6301 if (connection->responsive) {
6302 // The connection was unresponsive, and now it's responsive.
6303 processConnectionResponsiveLocked(*connection);
6304 }
6305 }
6306 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006307 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006308 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6309 // Only dispatch fallbacks if there is a window for the connection.
6310 if (windowHandle != nullptr) {
6311 const auto inputTarget =
6312 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6313 dispatchEntry->targetFlags,
6314 fallbackKeyEntry->downTime);
6315 if (inputTarget.has_value()) {
6316 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6317 *inputTarget);
6318 }
6319 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006321 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006322 }
6323
6324 // Start the next dispatch cycle for this connection.
6325 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326}
6327
Prabir Pradhancef936d2021-07-21 16:17:52 +00006328void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6329 const sp<IBinder>& newToken) {
6330 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6331 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006332 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 };
6334 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335}
6336
Prabir Pradhancef936d2021-07-21 16:17:52 +00006337void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6338 auto command = [this, token, x, y]() REQUIRES(mLock) {
6339 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006340 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006341 };
6342 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006343}
6344
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006345void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006346 if (connection == nullptr) {
6347 LOG_ALWAYS_FATAL("Caller must check for nullness");
6348 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006349 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6350 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006351 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006352 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006353 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006354 return;
6355 }
6356 /**
6357 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6358 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6359 * has changed. This could cause newer entries to time out before the already dispatched
6360 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6361 * processes the events linearly. So providing information about the oldest entry seems to be
6362 * most useful.
6363 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006364 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6365 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006366 std::string reason =
6367 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006368 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006369 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006370 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006371 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006372 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006373
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006374 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6375
6376 // Stop waking up for events on this connection, it is already unresponsive
6377 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006378}
6379
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006380void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6381 std::string reason =
6382 StringPrintf("%s does not have a focused window", application->getName().c_str());
6383 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006384
Yabin Cui8eb9c552023-06-08 18:05:07 +00006385 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006386 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006387 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006388 };
6389 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006390}
6391
chaviw98318de2021-05-19 16:45:23 -05006392void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006393 const std::string& reason) {
6394 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6395 updateLastAnrStateLocked(windowLabel, reason);
6396}
6397
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006398void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6399 const std::string& reason) {
6400 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006401 updateLastAnrStateLocked(windowLabel, reason);
6402}
6403
6404void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6405 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006407 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 struct tm tm;
6409 localtime_r(&t, &tm);
6410 char timestr[64];
6411 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006412 mLastAnrState.clear();
6413 mLastAnrState += INDENT "ANR:\n";
6414 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006415 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6416 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006417 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006418}
6419
Prabir Pradhancef936d2021-07-21 16:17:52 +00006420void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006421 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006422 const KeyEvent event = createKeyEvent(entry);
6423 nsecs_t delay = 0;
6424 { // release lock
6425 scoped_unlock unlock(mLock);
6426 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006427 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006428 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6429 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6430 std::to_string(t.duration().count()).c_str());
6431 }
6432 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433
6434 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006435 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006436 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006437 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006439 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006440 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442}
6443
Prabir Pradhancef936d2021-07-21 16:17:52 +00006444void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006445 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006446 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006447 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006448 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006449 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006450 };
6451 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006452}
6453
Prabir Pradhanedd96402022-02-15 01:46:16 -08006454void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006455 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006456 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006457 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006458 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006459 };
6460 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006461}
6462
6463/**
6464 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6465 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6466 * command entry to the command queue.
6467 */
6468void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6469 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006470 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006471 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006472 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006473 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006474 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006475 pid = findMonitorPidByTokenLocked(connectionToken);
6476 } else {
6477 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006478 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006479 reason.c_str());
6480 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6481 if (handle != nullptr) {
6482 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006483 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006484 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006485 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006486}
6487
6488/**
6489 * Tell the policy that a connection has become responsive so that it can stop ANR.
6490 */
6491void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006492 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006493 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006494 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006495 pid = findMonitorPidByTokenLocked(connectionToken);
6496 } else {
6497 // The connection is a window
6498 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6499 if (handle != nullptr) {
6500 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006501 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006502 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006503 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006504}
6505
Prabir Pradhan24047542023-11-02 17:14:59 +00006506std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006507 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006508 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006509 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006510 if (!handled) {
6511 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006512 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006513 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006514 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517 // Get the fallback key state.
6518 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006519 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006520 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006521 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522 connection->inputState.removeFallbackKey(originalKeyCode);
6523 }
6524
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006525 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006526 // If the application handles the original key for which we previously
6527 // generated a fallback or if the window is not a foreground window,
6528 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006529 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006531 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6532 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6533 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6534 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6535 keyEntry.policyFlags);
6536 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006537 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539
6540 mLock.unlock();
6541
Prabir Pradhana41d2442023-04-20 21:30:40 +00006542 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006543 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6544 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006545 unhandledKeyFallback) {
6546 event = *unhandledKeyFallback;
6547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548
6549 mLock.lock();
6550
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006551 // Cancel the fallback key, but only if we still have a window for the channel.
6552 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006553 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006554 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6555 if (windowHandle != nullptr) {
6556 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6557 "application handled the original non-fallback key "
6558 "or is no longer a foreground target, "
6559 "canceling previously dispatched fallback key");
6560 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006561 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006563 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006564 connection->inputState.removeFallbackKey(originalKeyCode);
6565 }
6566 } else {
6567 // If the application did not handle a non-fallback key, first check
6568 // that we are in a good state to perform unhandled key event processing
6569 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006570 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006571 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006572 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6573 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6574 "since this is not an initial down. "
6575 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6576 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6577 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006578 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6583 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6584 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6585 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6586 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006587 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006588
6589 mLock.unlock();
6590
Prabir Pradhana41d2442023-04-20 21:30:40 +00006591 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006592 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6593 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006594 fb) {
6595 fallback = true;
6596 event = *fb;
6597 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006598
6599 mLock.lock();
6600
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006601 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006602 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006603 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006604 }
6605
6606 // Latch the fallback keycode for this key on an initial down.
6607 // The fallback keycode cannot change at any other point in the lifecycle.
6608 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006610 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006611 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006612 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006613 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006614 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006615 }
6616
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006617 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618
6619 // Cancel the fallback key if the policy decides not to send it anymore.
6620 // We will continue to dispatch the key to the policy but we will no
6621 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006622 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6623 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6625 if (fallback) {
6626 ALOGD("Unhandled key event: Policy requested to send key %d"
6627 "as a fallback for %d, but on the DOWN it had requested "
6628 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006630 } else {
6631 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6632 "but on the DOWN it had requested to send %d. "
6633 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006634 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006635 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006636 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006637
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006638 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6639 if (windowHandle != nullptr) {
6640 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6641 "canceling fallback, policy no longer desires it");
6642 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006643 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006644 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006645
6646 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006647 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006648 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006649 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006650 }
6651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006653 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6654 {
6655 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006656 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006657 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006658 for (const auto& [key, value] : fallbackKeys) {
6659 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006660 }
6661 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6662 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006664 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006665
6666 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006667 // Return the fallback key that we want dispatched to the channel.
6668 std::unique_ptr<KeyEntry> newEntry =
6669 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6670 event.getEventTime(), event.getDeviceId(),
6671 event.getSource(), event.getDisplayId(),
6672 keyEntry.policyFlags, keyEntry.action,
6673 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6674 *fallbackKeyCode, event.getScanCode(),
6675 event.getMetaState(), event.getRepeatCount(),
6676 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006677 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6678 ALOGD("Unhandled key event: Dispatching fallback key. "
6679 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006680 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006681 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006682 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006683 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006684 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6685 ALOGD("Unhandled key event: No fallback key.");
6686 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006687
6688 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006689 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690 }
6691 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006692 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693}
6694
Michael Wrightd02c5b62014-02-10 15:10:22 -08006695void InputDispatcher::traceInboundQueueLengthLocked() {
6696 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006697 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006698 }
6699}
6700
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006701void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 if (ATRACE_ENABLED()) {
6703 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006704 snprintf(counterName, sizeof(counterName), "oq:%s",
6705 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006706 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006707 }
6708}
6709
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006710void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006711 if (ATRACE_ENABLED()) {
6712 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006713 snprintf(counterName, sizeof(counterName), "wq:%s",
6714 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006715 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006716 }
6717}
6718
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006719void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006720 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006721
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006722 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006723 dumpDispatchStateLocked(dump);
6724
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006725 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006726 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006727 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728 }
6729}
6730
6731void InputDispatcher::monitor() {
6732 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006733 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006734 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006735 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006736}
6737
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006738/**
6739 * Wake up the dispatcher and wait until it processes all events and commands.
6740 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6741 * this method can be safely called from any thread, as long as you've ensured that
6742 * the work you are interested in completing has already been queued.
6743 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006744bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006745 /**
6746 * Timeout should represent the longest possible time that a device might spend processing
6747 * events and commands.
6748 */
6749 constexpr std::chrono::duration TIMEOUT = 100ms;
6750 std::unique_lock lock(mLock);
6751 mLooper->wake();
6752 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6753 return result == std::cv_status::no_timeout;
6754}
6755
Vishnu Naire798b472020-07-23 13:52:21 -07006756/**
6757 * Sets focus to the window identified by the token. This must be called
6758 * after updating any input window handles.
6759 *
6760 * Params:
6761 * request.token - input channel token used to identify the window that should gain focus.
6762 * request.focusedToken - the token that the caller expects currently to be focused. If the
6763 * specified token does not match the currently focused window, this request will be dropped.
6764 * If the specified focused token matches the currently focused window, the call will succeed.
6765 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6766 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6767 * when requesting the focus change. This determines which request gets
6768 * precedence if there is a focus change request from another source such as pointer down.
6769 */
Vishnu Nair958da932020-08-21 17:12:37 -07006770void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6771 { // acquire lock
6772 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006773 std::optional<FocusResolver::FocusChanges> changes =
6774 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6775 if (changes) {
6776 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006777 }
6778 } // release lock
6779 // Wake up poll loop since it may need to make new input dispatching choices.
6780 mLooper->wake();
6781}
6782
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006783void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6784 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006785 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006786 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6787 ? removedFocusedWindowHandle
6788 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6789 if (resolvedWindow == nullptr) {
6790 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006791 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006792 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6793 "focus left window");
6794 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6795 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006796 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006797 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006798 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006799 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006800 }
6801
Prabir Pradhan99987712020-11-10 18:43:05 -08006802 // If a window has pointer capture, then it must have focus. We need to ensure that this
6803 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6804 // If the window loses focus before it loses pointer capture, then the window can be in a state
6805 // where it has pointer capture but not focus, violating the contract. Therefore we must
6806 // dispatch the pointer capture event before the focus event. Since focus events are added to
6807 // the front of the queue (above), we add the pointer capture event to the front of the queue
6808 // after the focus events are added. This ensures the pointer capture event ends up at the
6809 // front.
6810 disablePointerCaptureForcedLocked();
6811
Vishnu Nairc519ff72021-01-21 08:23:08 -08006812 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006813 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006814 }
6815}
Vishnu Nair958da932020-08-21 17:12:37 -07006816
Prabir Pradhan99987712020-11-10 18:43:05 -08006817void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006818 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006819 return;
6820 }
6821
6822 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6823
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006824 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006825 setPointerCaptureLocked(false);
6826 }
6827
6828 if (!mWindowTokenWithPointerCapture) {
6829 // No need to send capture changes because no window has capture.
6830 return;
6831 }
6832
6833 if (mPendingEvent != nullptr) {
6834 // Move the pending event to the front of the queue. This will give the chance
6835 // for the pending event to be dropped if it is a captured event.
6836 mInboundQueue.push_front(mPendingEvent);
6837 mPendingEvent = nullptr;
6838 }
6839
6840 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006841 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006842 mInboundQueue.push_front(std::move(entry));
6843}
6844
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006845void InputDispatcher::setPointerCaptureLocked(bool enable) {
6846 mCurrentPointerCaptureRequest.enable = enable;
6847 mCurrentPointerCaptureRequest.seq++;
6848 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006849 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006850 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006851 };
6852 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006853}
6854
Vishnu Nair599f1412021-06-21 10:39:58 -07006855void InputDispatcher::displayRemoved(int32_t displayId) {
6856 { // acquire lock
6857 std::scoped_lock _l(mLock);
6858 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006859 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006860 setFocusedApplicationLocked(displayId, nullptr);
6861 // Call focus resolver to clean up stale requests. This must be called after input windows
6862 // have been removed for the removed display.
6863 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006864 // Reset pointer capture eligibility, regardless of previous state.
6865 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006866 // Remove the associated touch mode state.
6867 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006868 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006869 } // release lock
6870
6871 // Wake up poll loop since it may need to make new input dispatching choices.
6872 mLooper->wake();
6873}
6874
Patrick Williamsd828f302023-04-28 17:52:08 -05006875void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006876 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6877 {
6878 // acquire lock
6879 std::scoped_lock _l(mLock);
6880 logDispatchStateLocked();
6881 }
6882 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6883 result.error().message().c_str());
6884 };
chaviw15fab6f2021-06-07 14:15:52 -05006885 // The listener sends the windows as a flattened array. Separate the windows by display for
6886 // more convenient parsing.
6887 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006888 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006889 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006890 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006891 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006892
6893 { // acquire lock
6894 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006895
6896 // Ensure that we have an entry created for all existing displays so that if a displayId has
6897 // no windows, we can tell that the windows were removed from the display.
6898 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6899 handlesPerDisplay[displayId];
6900 }
6901
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006902 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006903 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006904 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6905 }
6906
6907 for (const auto& [displayId, handles] : handlesPerDisplay) {
6908 setInputWindowsLocked(handles, displayId);
6909 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006910
6911 if (update.vsyncId < mWindowInfosVsyncId) {
6912 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6913 ", current update vsync id: %" PRId64,
6914 mWindowInfosVsyncId, update.vsyncId);
6915 }
6916 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006917 }
6918 // Wake up poll loop since it may need to make new input dispatching choices.
6919 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006920}
6921
Vishnu Nair062a8672021-09-03 16:07:44 -07006922bool InputDispatcher::shouldDropInput(
6923 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006924 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6925 (windowHandle->getInfo()->inputConfig.test(
6926 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006927 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006928 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6929 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006930 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006931 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006932 windowHandle->getInfo()->displayId);
6933 return true;
6934 }
6935 return false;
6936}
6937
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006938void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006939 const gui::WindowInfosUpdate& update) {
6940 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006941}
6942
Arthur Hungdfd528e2021-12-08 13:23:04 +00006943void InputDispatcher::cancelCurrentTouch() {
6944 {
6945 std::scoped_lock _l(mLock);
6946 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006947 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006948 "cancel current touch");
6949 synthesizeCancelationEventsForAllConnectionsLocked(options);
6950
6951 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006952 }
6953 // Wake up poll loop since there might be work to do.
6954 mLooper->wake();
6955}
6956
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006957void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6958 std::scoped_lock _l(mLock);
6959 mMonitorDispatchingTimeout = timeout;
6960}
6961
Arthur Hungc539dbb2022-12-08 07:45:36 +00006962void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6963 const sp<WindowInfoHandle>& oldWindowHandle,
6964 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006965 TouchState& state, int32_t deviceId,
6966 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006967 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006968 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6970 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6971 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6972 newWindowHandle->getInfo()->inputConfig.test(
6973 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6974 const sp<WindowInfoHandle> oldWallpaper =
6975 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6976 const sp<WindowInfoHandle> newWallpaper =
6977 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6978 if (oldWallpaper == newWallpaper) {
6979 return;
6980 }
6981
6982 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006983 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006984 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006985 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006986 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006987 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006988 }
6989
6990 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006991 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6992 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006993 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006994 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006995 }
6996}
6997
6998void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6999 ftl::Flags<InputTarget::Flags> newTargetFlags,
7000 const sp<WindowInfoHandle> fromWindowHandle,
7001 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07007002 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007003 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00007004 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7005 fromWindowHandle->getInfo()->inputConfig.test(
7006 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7007 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7008 toWindowHandle->getInfo()->inputConfig.test(
7009 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7010
7011 const sp<WindowInfoHandle> oldWallpaper =
7012 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
7013 const sp<WindowInfoHandle> newWallpaper =
7014 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
7015 if (oldWallpaper == newWallpaper) {
7016 return;
7017 }
7018
7019 if (oldWallpaper != nullptr) {
7020 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
7021 "transferring touch focus to another window");
7022 state.removeWindowByToken(oldWallpaper->getToken());
7023 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7024 }
7025
7026 if (newWallpaper != nullptr) {
7027 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007028 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7029 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007030 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7031 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007032 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007033 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007034 std::shared_ptr<Connection> wallpaperConnection =
7035 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007036 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007037 std::shared_ptr<Connection> toConnection =
7038 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007039 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7040 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7041 wallpaperFlags);
7042 }
7043 }
7044}
7045
7046sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7047 const sp<WindowInfoHandle>& windowHandle) const {
7048 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7049 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7050 bool foundWindow = false;
7051 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7052 if (!foundWindow && otherHandle != windowHandle) {
7053 continue;
7054 }
7055 if (windowHandle == otherHandle) {
7056 foundWindow = true;
7057 continue;
7058 }
7059
7060 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7061 return otherHandle;
7062 }
7063 }
7064 return nullptr;
7065}
7066
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007067void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7068 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007069 std::scoped_lock _l(mLock);
7070
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007071 mConfig.keyRepeatTimeout = timeout.count();
7072 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007073}
7074
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007075bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7076 DeviceId deviceId, int32_t pointerId) {
7077 std::scoped_lock _l(mLock);
7078 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7079 if (touchStateIt == mTouchStatesByDisplay.end()) {
7080 return false;
7081 }
7082 for (const TouchedWindow& window : touchStateIt->second.windows) {
7083 if (window.windowHandle->getToken() == token &&
7084 (window.hasTouchingPointer(deviceId, pointerId) ||
7085 window.hasHoveringPointer(deviceId, pointerId))) {
7086 return true;
7087 }
7088 }
7089 return false;
7090}
7091
Garfield Tane84e6f92019-08-29 17:28:41 -07007092} // namespace android::inputdispatcher