blob: d1dc1ee4a311e54246bdc83c077b7eac666369e5 [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.
Prabir Pradhanf4099452024-04-12 18:34:14 +000091std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000092 if (!isInputTracingEnabled()) {
93 return nullptr;
94 }
95 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
Prabir Pradhanf4099452024-04-12 18:34:14 +000096 trace::impl::PerfettoBackend());
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000097}
98
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000099template <class Entry>
100void ensureEventTraced(const Entry& entry) {
101 if (!entry.traceTracker) {
102 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
103 }
104}
105
Prabir Pradhan052fb0b2024-02-23 21:03:12 +0000106// Helper to get a trace tracker from a traced key or motion entry.
107const std::unique_ptr<trace::EventTrackerInterface>& getTraceTracker(const EventEntry& entry) {
108 switch (entry.type) {
109 case EventEntry::Type::MOTION: {
110 const auto& motion = static_cast<const MotionEntry&>(entry);
111 ensureEventTraced(motion);
112 return motion.traceTracker;
113 }
114 case EventEntry::Type::KEY: {
115 const auto& key = static_cast<const KeyEntry&>(entry);
116 ensureEventTraced(key);
117 return key.traceTracker;
118 }
119 default: {
120 const static std::unique_ptr<trace::EventTrackerInterface> kNullTracker;
121 return kNullTracker;
122 }
123 }
124}
125
Prabir Pradhancef936d2021-07-21 16:17:52 +0000126// Temporarily releases a held mutex for the lifetime of the instance.
127// Named to match std::scoped_lock
128class scoped_unlock {
129public:
130 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
131 ~scoped_unlock() { mMutex.lock(); }
132
133private:
134 std::mutex& mMutex;
135};
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Default input dispatching timeout if there is no focused application or paused window
138// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800139const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
140 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
141 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800143// The default minimum time gap between two user activity poke events.
144const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
145
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800146const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000149constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
150
151// Log a warning when an interception call takes longer than this to process.
152constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153
154// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000155constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
156
Antonio Kantekea47acb2021-12-23 12:41:25 -0800157// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000158constexpr int LOGTAG_INPUT_INTERACTION = 62000;
159constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000160constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000161
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000162const ui::Transform kIdentityTransform;
163
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000164inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 return systemTime(SYSTEM_TIME_MONOTONIC);
166}
167
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700168inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000169 if (binder == nullptr) {
170 return "<null>";
171 }
172 return StringPrintf("%p", binder.get());
173}
174
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000175static std::string uidString(const gui::Uid& uid) {
176 return uid.toString();
177}
178
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 case AKEY_EVENT_ACTION_DOWN:
182 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700183 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700185 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 }
187}
188
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700189Result<void> validateKeyEvent(int32_t action) {
190 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191}
192
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800194 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700196 case AMOTION_EVENT_ACTION_UP: {
197 if (pointerCount != 1) {
198 return Error() << "invalid pointer count " << pointerCount;
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 case AMOTION_EVENT_ACTION_HOVER_ENTER:
204 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700205 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
206 if (pointerCount < 1) {
207 return Error() << "invalid pointer count " << pointerCount;
208 }
209 return {};
210 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800211 case AMOTION_EVENT_ACTION_CANCEL:
212 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 case AMOTION_EVENT_ACTION_POINTER_DOWN:
216 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800217 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 if (index < 0) {
219 return Error() << "invalid index " << index << " for "
220 << MotionEvent::actionToString(action);
221 }
222 if (index >= pointerCount) {
223 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
224 }
225 if (pointerCount <= 1) {
226 return Error() << "invalid pointer count " << pointerCount << " for "
227 << MotionEvent::actionToString(action);
228 }
229 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700230 }
231 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
233 if (actionButton == 0) {
234 return Error() << "action button should be nonzero for "
235 << MotionEvent::actionToString(action);
236 }
237 return {};
238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700239 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 }
242}
243
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000244int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500245 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
246}
247
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700248Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
249 const PointerProperties* pointerProperties) {
250 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
251 if (!actionCheck.ok()) {
252 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 }
254 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700255 return Error() << "Motion event has invalid pointer count " << pointerCount
256 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800258 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 for (size_t i = 0; i < pointerCount; i++) {
260 int32_t id = pointerProperties[i].id;
261 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700262 return Error() << "Motion event has invalid pointer id " << id
263 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800265 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700266 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800268 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700270 return {};
271}
272
273Result<void> validateInputEvent(const InputEvent& event) {
274 switch (event.getType()) {
275 case InputEventType::KEY: {
276 const KeyEvent& key = static_cast<const KeyEvent&>(event);
277 const int32_t action = key.getAction();
278 return validateKeyEvent(action);
279 }
280 case InputEventType::MOTION: {
281 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
282 const int32_t action = motion.getAction();
283 const size_t pointerCount = motion.getPointerCount();
284 const PointerProperties* pointerProperties = motion.getPointerProperties();
285 const int32_t actionButton = motion.getActionButton();
286 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
287 }
288 default: {
289 return {};
290 }
291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292}
293
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800294std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
295 std::bitset<MAX_POINTER_ID + 1> pointerIds;
296 for (const PointerProperties& pointer : pointers) {
297 pointerIds.set(pointer.id);
298 }
299 return pointerIds;
300}
301
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000302std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000304 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 }
306
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000307 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 bool first = true;
309 Region::const_iterator cur = region.begin();
310 Region::const_iterator const tail = region.end();
311 while (cur != tail) {
312 if (first) {
313 first = false;
314 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800315 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800317 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318 cur++;
319 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000320 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321}
322
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000323std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
324 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500325 constexpr size_t maxEntries = 50; // max events to print
326 constexpr size_t skipBegin = maxEntries / 2;
327 const size_t skipEnd = queue.size() - maxEntries / 2;
328 // skip from maxEntries / 2 ... size() - maxEntries/2
329 // only print from 0 .. skipBegin and then from skipEnd .. size()
330
331 std::string dump;
332 for (size_t i = 0; i < queue.size(); i++) {
333 const DispatchEntry& entry = *queue[i];
334 if (i >= skipBegin && i < skipEnd) {
335 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
336 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
337 continue;
338 }
339 dump.append(INDENT4);
340 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000341 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
342 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500343 ns2ms(currentTime - entry.eventEntry->eventTime));
344 if (entry.deliveryTime != 0) {
345 // This entry was delivered, so add information on how long we've been waiting
346 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
347 }
348 dump.append("\n");
349 }
350 return dump;
351}
352
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700353/**
354 * Find the entry in std::unordered_map by key, and return it.
355 * If the entry is not found, return a default constructed entry.
356 *
357 * Useful when the entries are vectors, since an empty vector will be returned
358 * if the entry is not found.
359 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
360 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700361template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700363 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700364 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800365}
366
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700368 if (first == second) {
369 return true;
370 }
371
372 if (first == nullptr || second == nullptr) {
373 return false;
374 }
375
376 return first->getToken() == second->getToken();
377}
378
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000379bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000380 if (first == nullptr || second == nullptr) {
381 return false;
382 }
383 return first->applicationInfo.token != nullptr &&
384 first->applicationInfo.token == second->applicationInfo.token;
385}
386
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800387template <typename T>
388size_t firstMarkedBit(T set) {
389 // TODO: replace with std::countr_zero from <bit> when that's available
390 LOG_ALWAYS_FATAL_IF(set.none());
391 size_t i = 0;
392 while (!set.test(i)) {
393 i++;
394 }
395 return i;
396}
397
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000398std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
399 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000400 std::shared_ptr<const EventEntry> eventEntry,
401 ftl::Flags<InputTarget::Flags> inputTargetFlags,
Prabir Pradhana67623c2024-02-21 06:57:36 +0000402 int64_t vsyncId,
403 trace::InputTracerInterface* tracer) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000404 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000405 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
406 const std::optional<int32_t> windowId =
407 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
408 // Assume the only targets that are not associated with a window are global monitors, and use
409 // the system UID for global monitors for tracing purposes.
410 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000411
412 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700413 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700414 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700415 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000416 inputTarget.globalScaleFactor, uid, vsyncId,
417 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000418 }
419
420 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
421 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
422
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000423 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000424
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000425 const ui::Transform* transform = &kIdentityTransform;
426 const ui::Transform* displayTransform = &kIdentityTransform;
427 if (zeroCoords) {
428 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
429 } else {
430 // Use the first pointer information to normalize all other pointers. This could be any
431 // pointer as long as all other pointers are normalized to the same value and the final
432 // DispatchEntry uses the transform for the normalized pointer.
433 transform =
434 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
435 const ui::Transform inverseTransform = transform->inverse();
436 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000437
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000438 // Iterate through all pointers in the event to normalize against the first.
439 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
440 PointerCoords& newCoords = pointerCoords[i];
441 const auto pointerId = motionEntry.pointerProperties[i].id;
442 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000443
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000444 newCoords.copyFrom(motionEntry.pointerCoords[i]);
445 // First, apply the current pointer's transform to update the coordinates into
446 // window space.
Prabir Pradhan4b8d36c2024-06-07 15:10:46 +0000447 MotionEvent::calculateTransformedCoordsInPlace(newCoords, motionEntry.source,
448 motionEntry.flags, currTransform);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000449 // Next, apply the inverse transform of the normalized coordinates so the
450 // current coordinates are transformed into the normalized coordinate space.
Prabir Pradhan4b8d36c2024-06-07 15:10:46 +0000451 MotionEvent::calculateTransformedCoordsInPlace(newCoords, motionEntry.source,
452 motionEntry.flags, inverseTransform);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000453 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000454 }
455
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700456 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000457 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000458 motionEntry.eventTime, motionEntry.deviceId,
459 motionEntry.source, motionEntry.displayId,
460 motionEntry.policyFlags, motionEntry.action,
461 motionEntry.actionButton, motionEntry.flags,
462 motionEntry.metaState, motionEntry.buttonState,
463 motionEntry.classification, motionEntry.edgeFlags,
464 motionEntry.xPrecision, motionEntry.yPrecision,
465 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
466 motionEntry.downTime, motionEntry.pointerProperties,
467 pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +0000468 if (tracer) {
469 combinedMotionEntry->traceTracker =
470 tracer->traceDerivedEvent(*combinedMotionEntry, *motionEntry.traceTracker);
471 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000472
473 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700474 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000475 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000476 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000477 return dispatchEntry;
478}
479
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500480template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000481bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500482 if (lhs == nullptr && rhs == nullptr) {
483 return true;
484 }
485 if (lhs == nullptr || rhs == nullptr) {
486 return false;
487 }
488 return *lhs == *rhs;
489}
490
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000491KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000492 KeyEvent event;
493 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
494 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
495 entry.repeatCount, entry.downTime, entry.eventTime);
496 return event;
497}
498
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000499bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000500 // Do not keep track of gesture monitors. They receive every event and would disproportionately
501 // affect the statistics.
502 if (connection.monitor) {
503 return false;
504 }
505 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
506 if (!connection.responsive) {
507 return false;
508 }
509 return true;
510}
511
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000512bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000513 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
514 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000515 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
516 return false;
517 }
518 // Only track latency for events that originated from hardware
519 if (eventEntry.isSynthesized()) {
520 return false;
521 }
522 const EventEntry::Type& inputEventEntryType = eventEntry.type;
523 if (inputEventEntryType == EventEntry::Type::KEY) {
524 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
525 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
526 return false;
527 }
528 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
529 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
530 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
531 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
532 return false;
533 }
534 } else {
535 // Not a key or a motion
536 return false;
537 }
538 if (!shouldReportMetricsForConnection(connection)) {
539 return false;
540 }
541 return true;
542}
543
Prabir Pradhancef936d2021-07-21 16:17:52 +0000544/**
545 * Connection is responsive if it has no events in the waitQueue that are older than the
546 * current time.
547 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000548bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000549 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000550 for (const auto& dispatchEntry : connection.waitQueue) {
551 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000552 return false;
553 }
554 }
555 return true;
556}
557
Antonio Kantekf16f2832021-09-28 04:39:20 +0000558// Returns true if the event type passed as argument represents a user activity.
559bool isUserActivityEvent(const EventEntry& eventEntry) {
560 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000561 case EventEntry::Type::DEVICE_RESET:
562 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000563 case EventEntry::Type::FOCUS:
564 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000565 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000566 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000567 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000568 case EventEntry::Type::KEY:
569 case EventEntry::Type::MOTION:
570 return true;
571 }
572}
573
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800574// Returns true if the given window can accept pointer events at the given display location.
Linnan Li13bf76a2024-05-05 19:18:02 +0800575bool windowAcceptsTouchAt(const WindowInfo& windowInfo, ui::LogicalDisplayId displayId, float x,
576 float y, bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800577 const auto inputConfig = windowInfo.inputConfig;
578 if (windowInfo.displayId != displayId ||
579 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800580 return false;
581 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700582 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800583 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800584 return false;
585 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000586
587 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
588 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
589 // the window. Points on the right and bottom edges should not be inside the window, so we need
590 // to be careful about performing a hit test when the display is rotated, since the "right" and
591 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
592 // logical display in which WM determined the bounds. Perform the hit test in the logical
593 // display space to ensure these edges are considered correctly in all orientations.
594 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
595 const auto p = displayTransform.transform(x, y);
596 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800597 return false;
598 }
599 return true;
600}
601
Linnan Li5e5645e2024-03-05 14:43:05 +0000602// Returns true if the given window's frame can occlude pointer events at the given display
603// location.
Linnan Li13bf76a2024-05-05 19:18:02 +0800604bool windowOccludesTouchAt(const WindowInfo& windowInfo, ui::LogicalDisplayId displayId, float x,
605 float y, const ui::Transform& displayTransform) {
Linnan Li5e5645e2024-03-05 14:43:05 +0000606 if (windowInfo.displayId != displayId) {
607 return false;
608 }
609 const auto frame = displayTransform.transform(windowInfo.frame);
610 const auto p = floor(displayTransform.transform(x, y));
611 return p.x >= frame.left && p.x < frame.right && p.y >= frame.top && p.y < frame.bottom;
612}
613
Prabir Pradhand65552b2021-10-07 11:23:50 -0700614bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
615 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000616 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700617}
618
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800619// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000620// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
621// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
622// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800623// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000624bool canReceiveForegroundTouches(const WindowInfo& info) {
625 // A non-touchable window can still receive touch events (e.g. in the case of
626 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
627 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
628}
629
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000630bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700631 if (windowHandle == nullptr) {
632 return false;
633 }
634 const WindowInfo* windowInfo = windowHandle->getInfo();
635 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
636 return true;
637 }
638 return false;
639}
640
Prabir Pradhan5735a322022-04-11 17:23:34 +0000641// Checks targeted injection using the window's owner's uid.
642// Returns an empty string if an entry can be sent to the given window, or an error message if the
643// entry is a targeted injection whose uid target doesn't match the window owner.
644std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
645 const EventEntry& entry) {
646 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
647 // The event was not injected, or the injected event does not target a window.
648 return {};
649 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000650 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000651 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000652 return StringPrintf("No valid window target for injection into uid %s.",
653 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000654 }
655 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000656 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
657 "owned by uid %s.",
658 uid.toString().c_str(), window->getName().c_str(),
659 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000660 }
661 return {};
662}
663
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000664std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700665 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
666 // Always dispatch mouse events to cursor position.
667 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000668 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700669 }
670
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700671 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000672 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
673 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700674}
675
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700676std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
677 if (eventEntry.type == EventEntry::Type::KEY) {
678 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
679 return keyEntry.downTime;
680 } else if (eventEntry.type == EventEntry::Type::MOTION) {
681 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
682 return motionEntry.downTime;
683 }
684 return std::nullopt;
685}
686
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687/**
688 * Compare the old touch state to the new touch state, and generate the corresponding touched
689 * windows (== input targets).
690 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
691 * If the pointer just entered the new window, produce HOVER_ENTER.
692 * For pointers remaining in the window, produce HOVER_MOVE.
693 */
694std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
695 const TouchState& newTouchState,
696 const MotionEntry& entry) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000697 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700698
699 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
700 // ACTION_SCROLL events should not affect the hovering pointer dispatch
701 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000702 }
Linnan Li41859c42024-03-05 16:20:34 +0000703 std::vector<TouchedWindow> out;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000704
705 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800706 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000707
708 std::set<sp<WindowInfoHandle>> oldWindows;
709 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800710 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000711 }
712
713 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800714 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000715
716 // If the pointer is no longer in the new window set, send HOVER_EXIT.
717 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
718 if (newWindows.find(oldWindow) == newWindows.end()) {
719 TouchedWindow touchedWindow;
720 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000721 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000722 out.push_back(touchedWindow);
723 }
724 }
725
726 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
727 TouchedWindow touchedWindow;
728 touchedWindow.windowHandle = newWindow;
729 if (oldWindows.find(newWindow) == oldWindows.end()) {
730 // Any windows that have this pointer now, and didn't have it before, should get
731 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000732 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000733 } else {
734 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700735 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700736 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000737 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
738 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700739 // The Accessibility injected touch exploration event stream
740 // has known inconsistencies, so log ERROR instead of
741 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700742 severity = android::base::LogSeverity::ERROR;
743 }
744 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700745 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000746 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000747 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800748 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000749 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
750 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
751 }
752 out.push_back(touchedWindow);
753 }
754 return out;
755}
756
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800757template <typename T>
758std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
759 left.insert(left.end(), right.begin(), right.end());
760 return left;
761}
762
Harry Cuttsb166c002023-05-09 13:06:05 +0000763// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
764// both.
765void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
766 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
767 if (!window.windowHandle->getInfo()->inputConfig.test(
768 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
769 // In addition to TouchState, erase this window from the input targets! We don't have a
770 // good way to do this today except by adding a nested loop.
771 // TODO(b/282025641): simplify this code once InputTargets are being identified
772 // separately from TouchedWindows.
773 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800774 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000775 });
776 return true;
777 }
778 return false;
779 });
780}
781
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700782/**
783 * In general, touch should be always split between windows. Some exceptions:
784 * 1. Don't split touch if all of the below is true:
785 * (a) we have an active pointer down *and*
786 * (b) a new pointer is going down that's from the same device *and*
787 * (c) the window that's receiving the current pointer does not support split touch.
788 * 2. Don't split mouse events
789 */
790bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
791 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
792 // We should never split mouse events
793 return false;
794 }
795 for (const TouchedWindow& touchedWindow : touchState.windows) {
796 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
797 // Spy windows should not affect whether or not touch is split.
798 continue;
799 }
800 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
801 continue;
802 }
803 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
804 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
805 // Wallpaper window should not affect whether or not touch is split
806 continue;
807 }
808
809 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
810 return false;
811 }
812 }
813 return true;
814}
815
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700816/**
817 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
818 */
Linnan Li13bf76a2024-05-05 19:18:02 +0800819bool isStylusActiveInDisplay(ui::LogicalDisplayId displayId,
820 const std::unordered_map<ui::LogicalDisplayId /*displayId*/,
821 TouchState>& touchStatesByDisplay) {
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700822 const auto it = touchStatesByDisplay.find(displayId);
823 if (it == touchStatesByDisplay.end()) {
824 return false;
825 }
826 const TouchState& state = it->second;
827 return state.hasActiveStylus();
828}
829
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800830Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
831 struct HashFunction {
832 size_t operator()(const WindowInfo& info) const { return info.id; }
833 };
834
835 std::unordered_set<WindowInfo, HashFunction> windowSet;
836 for (const WindowInfo& info : update.windowInfos) {
837 const auto [_, inserted] = windowSet.insert(info);
838 if (!inserted) {
839 return Error() << "Duplicate entry for " << info;
840 }
841 }
842 return {};
843}
844
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800845int32_t getUserActivityEventType(const EventEntry& eventEntry) {
846 switch (eventEntry.type) {
847 case EventEntry::Type::KEY: {
848 return USER_ACTIVITY_EVENT_BUTTON;
849 }
850 case EventEntry::Type::MOTION: {
851 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
852 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
853 return USER_ACTIVITY_EVENT_TOUCH;
854 }
855 return USER_ACTIVITY_EVENT_OTHER;
856 }
857 default: {
858 LOG_ALWAYS_FATAL("%s events are not user activity",
859 ftl::enum_string(eventEntry.type).c_str());
860 }
861 }
862}
863
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000864std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
865 CancelationOptions::Mode mode) {
866 switch (mode) {
867 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
868 return {true, true};
869 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
870 return {true, false};
871 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
872 return {false, true};
873 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
874 return {false, true};
875 }
876}
877
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000878class ScopedSyntheticEventTracer {
879public:
880 ScopedSyntheticEventTracer(std::unique_ptr<trace::InputTracerInterface>& tracer)
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000881 : mTracer(tracer), mProcessingTimestamp(now()) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000882 if (mTracer) {
883 mEventTracker = mTracer->createTrackerForSyntheticEvent();
884 }
885 }
886
887 ~ScopedSyntheticEventTracer() {
888 if (mTracer) {
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000889 mTracer->eventProcessingComplete(*mEventTracker, mProcessingTimestamp);
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000890 }
891 }
892
893 const std::unique_ptr<trace::EventTrackerInterface>& getTracker() const {
894 return mEventTracker;
895 }
896
897private:
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000898 const std::unique_ptr<trace::InputTracerInterface>& mTracer;
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000899 std::unique_ptr<trace::EventTrackerInterface> mEventTracker;
Prabir Pradhan4fc32e02024-06-14 16:00:58 +0000900 const nsecs_t mProcessingTimestamp;
Prabir Pradhand6b2b052024-02-21 23:25:15 +0000901};
902
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000903} // namespace
904
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905// --- InputDispatcher ---
906
Prabir Pradhana41d2442023-04-20 21:30:40 +0000907InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanf4099452024-04-12 18:34:14 +0000908 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000909
910InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
911 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700912 : mPolicy(policy),
913 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700914 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800915 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800916 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700917 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800918 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700919 mDispatchEnabled(false),
920 mDispatchFrozen(false),
921 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100922 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -0700923 mFocusedDisplayId(ui::LogicalDisplayId::DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800924 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -0700925 mAwaitedApplicationDisplayId(ui::LogicalDisplayId::INVALID),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000926 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000927 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700928 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800929 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700931 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700932#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700933 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700934#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700935 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000936
937 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000938 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000939 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800940
941 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942}
943
944InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000945 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946
Prabir Pradhancef936d2021-07-21 16:17:52 +0000947 resetKeyRepeatLocked();
948 releasePendingEventLocked();
949 drainInboundQueueLocked();
950 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000952 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700953 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800954 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956}
957
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700958status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700959 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700960 return ALREADY_EXISTS;
961 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700962 mThread = std::make_unique<InputThread>(
963 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
964 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700965}
966
967status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700968 if (mThread && mThread->isCallingThread()) {
969 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700970 return INVALID_OPERATION;
971 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700972 mThread.reset();
973 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700974}
975
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700977 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800979 std::scoped_lock _l(mLock);
980 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
982 // Run a dispatch loop if there are no pending commands.
983 // The dispatch loop might enqueue commands to run afterwards.
984 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800985 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 }
987
988 // Run all pending commands if there are any.
989 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000990 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700991 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800993
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700994 // If we are still waiting for ack on some events,
995 // we might have to wake up earlier to check if an app is anr'ing.
996 const nsecs_t nextAnrCheck = processAnrsLocked();
997 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
998
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800999 // We are about to enter an infinitely long sleep, because we have no commands or
1000 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -07001001 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001002 mDispatcherEnteredIdle.notify_all();
1003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 } // release lock
1005
1006 // Wait for callback or timeout or wake. (make sure we round up, not down)
1007 nsecs_t currentTime = now();
1008 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
1009 mLooper->pollOnce(timeoutMillis);
1010}
1011
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001012/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001013 * Raise ANR if there is no focused window.
1014 * Before the ANR is raised, do a final state check:
1015 * 1. The currently focused application must be the same one we are waiting for.
1016 * 2. Ensure we still don't have a focused window.
1017 */
1018void InputDispatcher::processNoFocusedWindowAnrLocked() {
1019 // Check if the application that we are waiting for is still focused.
1020 std::shared_ptr<InputApplicationHandle> focusedApplication =
1021 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
1022 if (focusedApplication == nullptr ||
1023 focusedApplication->getApplicationToken() !=
1024 mAwaitedFocusedApplication->getApplicationToken()) {
1025 // Unexpected because we should have reset the ANR timer when focused application changed
1026 ALOGE("Waited for a focused window, but focused application has already changed to %s",
1027 focusedApplication->getName().c_str());
1028 return; // The focused application has changed.
1029 }
1030
chaviw98318de2021-05-19 16:45:23 -05001031 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001032 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
1033 if (focusedWindowHandle != nullptr) {
1034 return; // We now have a focused window. No need for ANR.
1035 }
1036 onAnrLocked(mAwaitedFocusedApplication);
1037}
1038
1039/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040 * Check if any of the connections' wait queues have events that are too old.
1041 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
1042 * Return the time at which we should wake up next.
1043 */
1044nsecs_t InputDispatcher::processAnrsLocked() {
1045 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -07001046 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001047 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
1048 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
1049 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001050 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -07001051 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001052 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001053 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001054 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001055 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001056 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1057 }
1058 }
1059
1060 // Check if any connection ANRs are due
1061 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1062 if (currentTime < nextAnrCheck) { // most likely scenario
1063 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1064 }
1065
1066 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001067 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001068 if (connection == nullptr) {
1069 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1070 return nextAnrCheck;
1071 }
1072 connection->responsive = false;
1073 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001074 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001075 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001076 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001077}
1078
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001079std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001080 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001081 if (connection->monitor) {
1082 return mMonitorDispatchingTimeout;
1083 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001084 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001085 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001086 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001087 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001088 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001089}
1090
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001091void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 nsecs_t currentTime = now();
1093
Jeff Browndc5992e2014-04-11 01:27:26 -07001094 // Reset the key repeat timer whenever normal dispatch is suspended while the
1095 // device is in a non-interactive state. This is to ensure that we abort a key
1096 // repeat if the device is just coming out of sleep.
1097 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 resetKeyRepeatLocked();
1099 }
1100
1101 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1102 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001103 if (DEBUG_FOCUS) {
1104 ALOGD("Dispatch frozen. Waiting some more.");
1105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 return;
1107 }
1108
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 // Ready to start a new event.
1110 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001112 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 // Synthesize a key repeat if appropriate.
1114 if (mKeyRepeatState.lastKeyEntry) {
1115 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1116 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1117 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001118 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 }
1120 }
1121
1122 // Nothing to do if there is no pending event.
1123 if (!mPendingEvent) {
1124 return;
1125 }
1126 } else {
1127 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001128 mPendingEvent = mInboundQueue.front();
1129 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 traceInboundQueueLengthLocked();
1131 }
1132
1133 // Poke user activity for this event.
1134 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001135 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138
1139 // Now we have an event to dispatch.
1140 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001141 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001143 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001147 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149
1150 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001151 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
1153
1154 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001155 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 const DeviceResetEntry& typedEntry =
1157 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001159 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 break;
1161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001163 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001164 std::shared_ptr<const FocusEntry> typedEntry =
1165 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001166 dispatchFocusLocked(currentTime, typedEntry);
1167 done = true;
1168 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1169 break;
1170 }
1171
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001172 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001173 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001174 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1175 done = true;
1176 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1177 break;
1178 }
1179
Prabir Pradhan99987712020-11-10 18:43:05 -08001180 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1181 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001182 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001183 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1184 done = true;
1185 break;
1186 }
1187
arthurhungb89ccb02020-12-30 16:19:01 +08001188 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001189 std::shared_ptr<const DragEntry> typedEntry =
1190 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001191 dispatchDragLocked(currentTime, typedEntry);
1192 done = true;
1193 break;
1194 }
1195
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001197 std::shared_ptr<const KeyEntry> keyEntry =
1198 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001200 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001202 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1203 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 break;
1207 }
1208
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001209 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001210 std::shared_ptr<const MotionEntry> motionEntry =
1211 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001212 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001213 // The event is stale. However, only drop stale events if there isn't an ongoing
1214 // gesture. That would allow us to complete the processing of the current stroke.
1215 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1216 if (touchStateIt != mTouchStatesByDisplay.end()) {
1217 const TouchState& touchState = touchStateIt->second;
1218 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1219 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1220 dropReason = DropReason::STALE;
1221 }
1222 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001224 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001225 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1226 // Only drop events that are focus-dispatched.
1227 dropReason = DropReason::BLOCKED;
1228 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
Chris Yef59a2f42020-10-16 12:55:26 -07001233
1234 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001235 std::shared_ptr<const SensorEntry> sensorEntry =
1236 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001237
Chris Yef59a2f42020-10-16 12:55:26 -07001238 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1239 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1240 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1241 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1242 dropReason = DropReason::STALE;
1243 }
1244 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1245 done = true;
1246 break;
1247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249
1250 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001251 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001252 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
Michael Wright3a981722015-06-10 15:26:13 +01001254 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001256 if (mTracer) {
1257 if (auto& traceTracker = getTraceTracker(*mPendingEvent); traceTracker != nullptr) {
Prabir Pradhan4fc32e02024-06-14 16:00:58 +00001258 mTracer->eventProcessingComplete(*traceTracker, currentTime);
Prabir Pradhan052fb0b2024-02-23 21:03:12 +00001259 }
1260 }
1261
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001263 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265}
1266
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001267bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001268 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001269}
1270
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001271/**
1272 * Return true if the events preceding this incoming motion event should be dropped
1273 * Return false otherwise (the default behaviour)
1274 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001275bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001276 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001277 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001278
1279 // Optimize case where the current application is unresponsive and the user
1280 // decides to touch a window in a different application.
1281 // If the application takes too long to catch up then we drop all events preceding
1282 // the touch into the other window.
1283 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001284 const ui::LogicalDisplayId displayId = motionEntry.displayId;
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001285 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001286 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001287
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001288 sp<WindowInfoHandle> touchedWindowHandle =
1289 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001290 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001291 touchedWindowHandle->getApplicationToken() !=
1292 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001293 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001294 ALOGI("Pruning input queue because user touched a different application while waiting "
1295 "for %s",
1296 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001297 return true;
1298 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001299
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001300 // Alternatively, maybe there's a spy window that could handle this event.
1301 const std::vector<sp<WindowInfoHandle>> touchedSpies =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001302 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, motionEntry.deviceId);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001303 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001304 const std::shared_ptr<Connection> connection =
1305 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001306 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001307 // This spy window could take more input. Drop all events preceding this
1308 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001309 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001310 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001311 mAwaitedFocusedApplication->getName().c_str());
1312 return true;
1313 }
1314 }
1315 }
1316
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001317 return false;
1318}
1319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001320bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001323 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 traceInboundQueueLengthLocked();
1325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001326 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001327 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001328 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1329 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001332 if (mTracer) {
1333 ensureEventTraced(keyEntry);
1334 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001335
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001336 // If a new up event comes in, and the pending event with same key code has been asked
1337 // to try again later because of the policy. We have to reset the intercept key wake up
1338 // time for it may have been handled in the policy and could be dropped.
1339 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1340 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001341 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001342 if (pendingKey.keyCode == keyEntry.keyCode &&
1343 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001344 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1345 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001346 pendingKey.interceptKeyWakeupTime = 0;
1347 needWake = true;
1348 }
1349 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001350 break;
1351 }
1352
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001353 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001354 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1355 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001356 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1357 if (mTracer) {
1358 ensureEventTraced(motionEntry);
1359 }
1360 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001362 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001364
1365 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1366 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1367 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1368 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1369 // and some other events have not yet been processed, the dispatcher will wait for
1370 // these events to be processed before dispatching the key event. This is because
1371 // the unprocessed events may cause the focus to change (for example, by launching a
1372 // new window or tapping a different window). To prevent waiting too long, we force
1373 // the key to be sent to the currently focused window when a new tap comes in.
1374 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1375 "just send the pending key event to the currently focused window.");
1376 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001377 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001378 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001381 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001382 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1383 break;
1384 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001385 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001386 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001387 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001388 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1389 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001390 // nothing to do
1391 break;
1392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
1394
1395 return needWake;
1396}
1397
Prabir Pradhan24047542023-11-02 17:14:59 +00001398void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001399 // Do not store sensor event in recent queue to avoid flooding the queue.
1400 if (entry->type != EventEntry::Type::SENSOR) {
1401 mRecentQueue.push_back(entry);
1402 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001403 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001404 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 }
1406}
1407
Linnan Li13bf76a2024-05-05 19:18:02 +08001408sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(ui::LogicalDisplayId displayId,
1409 float x, float y, bool isStylus,
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001410 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001412 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001413 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001414 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001415 continue;
1416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001418 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001419 if (!info.isSpy() &&
1420 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001421 return windowHandle;
1422 }
1423 }
1424 return nullptr;
1425}
1426
1427std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08001428 ui::LogicalDisplayId displayId, const sp<WindowInfoHandle>& touchedWindow,
1429 int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001430 if (touchedWindow == nullptr) {
1431 return {};
1432 }
1433 // Traverse windows from front to back until we encounter the touched window.
1434 std::vector<InputTarget> outsideTargets;
1435 const auto& windowHandles = getWindowHandlesLocked(displayId);
1436 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1437 if (windowHandle == touchedWindow) {
1438 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1439 // below the touched window will not get ACTION_OUTSIDE event.
1440 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001441 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001442
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001443 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001444 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001445 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1446 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001447 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1448 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001449 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
1451 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001452 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453}
1454
Prabir Pradhand65552b2021-10-07 11:23:50 -07001455std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001456 ui::LogicalDisplayId displayId, float x, float y, bool isStylus, DeviceId deviceId) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001457 // Traverse windows from front to back and gather the touched spy windows.
1458 std::vector<sp<WindowInfoHandle>> spyWindows;
1459 const auto& windowHandles = getWindowHandlesLocked(displayId);
1460 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1461 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001462 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07001463 // Generally, we would skip any pointer that's outside of the window. However, if the
1464 // spy prevents splitting, and already has some of the pointers from this device, then
1465 // it should get more pointers from the same device, even if they are outside of that
1466 // window
1467 if (info.supportsSplitTouch()) {
1468 continue;
1469 }
1470
1471 // We know that split touch is not supported. Skip this window only if it doesn't have
1472 // any touching pointers for this device already.
1473 if (!windowHasTouchingPointersLocked(windowHandle, deviceId)) {
1474 continue;
1475 }
1476 // If it already has pointers down for this device, then give it this pointer, too.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001477 }
1478 if (!info.isSpy()) {
1479 // The first touched non-spy window was found, so return the spy windows touched so far.
1480 return spyWindows;
1481 }
1482 spyWindows.push_back(windowHandle);
1483 }
1484 return spyWindows;
1485}
1486
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001487void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 const char* reason;
1489 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001490 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001491 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001492 ALOGD("Dropped event because policy consumed it.");
1493 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 reason = "inbound event was dropped because the policy consumed it";
1495 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001496 case DropReason::DISABLED:
1497 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 ALOGI("Dropped event because input dispatch is disabled.");
1499 }
1500 reason = "inbound event was dropped because input dispatch is disabled";
1501 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001502 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001503 LOG(INFO) << "Dropping because the current application is not responding and the user "
1504 "has started interacting with a different application: "
1505 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001506 reason = "inbound event was dropped because the current application is not responding "
1507 "and the user has started interacting with a different application";
1508 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001509 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001510 ALOGI("Dropped event because it is stale.");
1511 reason = "inbound event was dropped because it is stale";
1512 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001513 case DropReason::NO_POINTER_CAPTURE:
1514 ALOGI("Dropped event because there is no window with Pointer Capture.");
1515 reason = "inbound event was dropped because there is no window with Pointer Capture";
1516 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001517 case DropReason::NOT_DROPPED: {
1518 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001519 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 }
1522
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001523 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001524 case EventEntry::Type::KEY: {
Hu Guo3cfa7382023-11-15 09:50:04 +00001525 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001526 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason,
1527 keyEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001528 options.displayId = keyEntry.displayId;
1529 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001531 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001533 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001534 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1535 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001536 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason,
1537 motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001538 options.displayId = motionEntry.displayId;
1539 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001540 synthesizeCancelationEventsForAllConnectionsLocked(options);
1541 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001542 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001543 reason, motionEntry.traceTracker);
Hu Guo3cfa7382023-11-15 09:50:04 +00001544 options.displayId = motionEntry.displayId;
1545 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001546 synthesizeCancelationEventsForAllConnectionsLocked(options);
1547 }
1548 break;
1549 }
Chris Yef59a2f42020-10-16 12:55:26 -07001550 case EventEntry::Type::SENSOR: {
1551 break;
1552 }
arthurhungb89ccb02020-12-30 16:19:01 +08001553 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1554 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001555 break;
1556 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001557 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001558 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001559 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001560 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001561 break;
1562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 }
1564}
1565
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001567 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568}
1569
Prabir Pradhancef936d2021-07-21 16:17:52 +00001570bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001571 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 return false;
1573 }
1574
1575 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001576 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001577 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001578 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1579 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001580 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 return true;
1582}
1583
Prabir Pradhancef936d2021-07-21 16:17:52 +00001584void InputDispatcher::postCommandLocked(Command&& command) {
1585 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586}
1587
1588void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001589 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001590 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001591 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 releaseInboundEventLocked(entry);
1593 }
1594 traceInboundQueueLengthLocked();
1595}
1596
1597void InputDispatcher::releasePendingEventLocked() {
1598 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001600 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 }
1602}
1603
Prabir Pradhan24047542023-11-02 17:14:59 +00001604void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001605 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001606 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001607 if (DEBUG_DISPATCH_CYCLE) {
1608 ALOGD("Injected inbound event was dropped.");
1609 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001610 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 }
1612 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001613 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 }
1615 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616}
1617
1618void InputDispatcher::resetKeyRepeatLocked() {
1619 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001620 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 }
1622}
1623
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001624std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001625 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626
Michael Wright2e732952014-09-24 13:26:59 -07001627 uint32_t policyFlags = entry->policyFlags &
1628 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001630 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001631 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1632 currentTime, entry->deviceId, entry->source,
1633 entry->displayId, policyFlags, entry->action, entry->flags,
1634 entry->keyCode, entry->scanCode, entry->metaState,
1635 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001637 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001638 if (mTracer) {
1639 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1640 }
1641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001644 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645}
1646
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001647bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1648 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001649 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1650 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1651 entry.deviceId);
1652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653
liushenxiang42232912021-05-21 20:24:09 +08001654 // Reset key repeating in case a keyboard device was disabled or enabled.
1655 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1656 resetKeyRepeatLocked();
1657 }
1658
Prabir Pradhand6b2b052024-02-21 23:25:15 +00001659 ScopedSyntheticEventTracer traceContext(mTracer);
1660 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset",
1661 traceContext.getTracker());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001662 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001664
1665 // Remove all active pointers from this device
1666 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1667 touchState.removeAllPointersForDevice(entry.deviceId);
1668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 return true;
1670}
1671
Vishnu Nairad321cd2020-08-20 16:40:21 -07001672void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001673 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001674 if (mPendingEvent != nullptr) {
1675 // Move the pending event to the front of the queue. This will give the chance
1676 // for the pending event to get dispatched to the newly focused window
1677 mInboundQueue.push_front(mPendingEvent);
1678 mPendingEvent = nullptr;
1679 }
1680
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001681 std::unique_ptr<FocusEntry> focusEntry =
1682 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1683 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001684
1685 // This event should go to the front of the queue, but behind all other focus events
1686 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001687 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1688 [](const std::shared_ptr<const EventEntry>& event) {
1689 return event->type == EventEntry::Type::FOCUS;
1690 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001691
1692 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001693 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001694}
1695
Prabir Pradhan24047542023-11-02 17:14:59 +00001696void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1697 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001698 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1699 if (connection == nullptr) {
1700 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001701 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001702 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001703 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001704 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001705 std::string reason = std::string("reason=").append(entry->reason);
1706 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001707 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001708}
1709
Prabir Pradhan99987712020-11-10 18:43:05 -08001710void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001711 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001712 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001713 dropReason = DropReason::NOT_DROPPED;
1714
Prabir Pradhan99987712020-11-10 18:43:05 -08001715 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001716 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001717
Hiroki Sato25040232024-02-22 17:21:22 +09001718 if (entry->pointerCaptureRequest.isEnable()) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001719 // Enable Pointer Capture.
1720 if (haveWindowWithPointerCapture &&
1721 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001722 // This can happen if pointer capture is disabled and re-enabled before we notify the
1723 // app of the state change, so there is no need to notify the app.
1724 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1725 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001726 }
Hiroki Sato25040232024-02-22 17:21:22 +09001727 if (!mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001728 // This can happen if a window requests capture and immediately releases capture.
1729 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001730 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001731 return;
1732 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001733 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1734 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1735 return;
1736 }
1737
Vishnu Nairc519ff72021-01-21 08:23:08 -08001738 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001739 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
Hiroki Sato25040232024-02-22 17:21:22 +09001740 LOG_ALWAYS_FATAL_IF(token != entry->pointerCaptureRequest.window,
1741 "Unexpected requested window for Pointer Capture.");
Prabir Pradhan99987712020-11-10 18:43:05 -08001742 mWindowTokenWithPointerCapture = token;
1743 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001744 // Disable Pointer Capture.
1745 // We do not check if the sequence number matches for requests to disable Pointer Capture
1746 // for two reasons:
1747 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1748 // to disable capture with the same sequence number: one generated by
1749 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1750 // Capture being disabled in InputReader.
1751 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1752 // actual Pointer Capture state that affects events being generated by input devices is
1753 // in InputReader.
1754 if (!haveWindowWithPointerCapture) {
1755 // Pointer capture was already forcefully disabled because of focus change.
1756 dropReason = DropReason::NOT_DROPPED;
1757 return;
1758 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001759 token = mWindowTokenWithPointerCapture;
1760 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001761 if (mCurrentPointerCaptureRequest.isEnable()) {
1762 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001763 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001764 }
1765
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001766 auto connection = getConnectionLocked(token);
1767 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001768 // Window has gone away, clean up Pointer Capture state.
1769 mWindowTokenWithPointerCapture = nullptr;
Hiroki Sato25040232024-02-22 17:21:22 +09001770 if (mCurrentPointerCaptureRequest.isEnable()) {
1771 setPointerCaptureLocked(nullptr);
Prabir Pradhan7d030382020-12-21 07:58:35 -08001772 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001773 return;
1774 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001775 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001776 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001777
1778 dropReason = DropReason::NOT_DROPPED;
1779}
1780
Prabir Pradhan24047542023-11-02 17:14:59 +00001781void InputDispatcher::dispatchTouchModeChangeLocked(
1782 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001783 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001784 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001785 if (windowHandles.empty()) {
1786 return;
1787 }
1788 const std::vector<InputTarget> inputTargets =
1789 getInputTargetsFromWindowHandlesLocked(windowHandles);
1790 if (inputTargets.empty()) {
1791 return;
1792 }
1793 entry->dispatchInProgress = true;
1794 dispatchEventLocked(currentTime, entry, inputTargets);
1795}
1796
1797std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1798 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1799 std::vector<InputTarget> inputTargets;
1800 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001801 const sp<IBinder>& token = handle->getToken();
1802 if (token == nullptr) {
1803 continue;
1804 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001805 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1806 if (connection == nullptr) {
1807 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001808 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001809 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001810 }
1811 return inputTargets;
1812}
1813
Prabir Pradhan24047542023-11-02 17:14:59 +00001814bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001815 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 if (!entry->dispatchInProgress) {
Hu Guofe3c8f12023-09-22 17:20:15 +08001818 if (!entry->syntheticRepeat && entry->action == AKEY_EVENT_ACTION_DOWN &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1820 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1821 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001822 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 // We have seen two identical key downs in a row which indicates that the device
1824 // driver is automatically generating key repeats itself. We take note of the
1825 // repeat here, but we disable our own next key repeat timer since it is clear that
1826 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001827 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1828 // Make sure we don't get key down from a different device. If a different
1829 // device Id has same key pressed down, the new device Id will replace the
1830 // current one to hold the key repeat with repeat count reset.
1831 // In the future when got a KEY_UP on the device id, drop it and do not
1832 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1834 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001835 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 } else {
1837 // Not a repeat. Save key down state in case we do see a repeat later.
1838 resetKeyRepeatLocked();
1839 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1840 }
1841 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001842 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1843 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001844 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001845 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001846 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1847 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 resetKeyRepeatLocked();
1850 }
1851
1852 if (entry->repeatCount == 1) {
1853 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1854 } else {
1855 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1856 }
1857
1858 entry->dispatchInProgress = true;
1859
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001860 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
1862
1863 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001864 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001866 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 return false; // wait until next wakeup
1868 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001869 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 entry->interceptKeyWakeupTime = 0;
1871 }
1872
1873 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001874 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001876 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001877 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001878
1879 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1880 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1881 };
1882 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 return false; // wait for the command to run
1884 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001885 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001887 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001888 if (*dropReason == DropReason::NOT_DROPPED) {
1889 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891 }
1892
1893 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001894 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001895 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1897 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001898 mReporter->reportDroppedKey(entry->id);
Josep del Rioc8fdedb2024-05-21 13:32:43 +00001899 // Poke user activity for consumed keys, as it may have not been reported due to
1900 // the focused window requesting user activity to be disabled
1901 if (*dropReason == DropReason::POLICY &&
1902 mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
1903 pokeUserActivityLocked(*entry);
1904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 return true;
1906 }
1907
1908 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001909 InputEventInjectionResult injectionResult;
1910 sp<WindowInfoHandle> focusedWindow =
1911 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1912 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 return false;
1915 }
1916
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001917 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 return true;
1920 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001921 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1922
1923 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001924 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1925 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001927 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001928 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001930 if (mTracer) {
1931 ensureEventTraced(*entry);
1932 for (const auto& target : inputTargets) {
1933 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1934 }
1935 }
1936
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 // Dispatch the key.
1938 dispatchEventLocked(currentTime, entry, inputTargets);
1939 return true;
1940}
1941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001942void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001943 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08001944 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001945 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1946 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Linnan Li13bf76a2024-05-05 19:18:02 +08001947 prefix, entry.eventTime, entry.deviceId, entry.source,
1948 entry.displayId.toString().c_str(), entry.policyFlags, entry.action, entry.flags,
1949 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount, entry.downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951}
1952
Prabir Pradhancef936d2021-07-21 16:17:52 +00001953void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001954 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001955 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001956 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1957 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1958 "source=0x%x, sensorType=%s",
1959 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001960 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001961 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001962 auto command = [this, entry]() REQUIRES(mLock) {
1963 scoped_unlock unlock(mLock);
1964
1965 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001966 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001967 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001968 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1969 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001970 };
1971 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001972}
1973
1974bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001975 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1976 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001977 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001978 }
Chris Yef59a2f42020-10-16 12:55:26 -07001979 { // acquire lock
1980 std::scoped_lock _l(mLock);
1981
1982 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001983 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001984 if (entry->type == EventEntry::Type::SENSOR) {
1985 it = mInboundQueue.erase(it);
1986 releaseInboundEventLocked(entry);
1987 }
1988 }
1989 }
1990 return true;
1991}
1992
Prabir Pradhan24047542023-11-02 17:14:59 +00001993bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1994 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001995 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001996 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001998 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 entry->dispatchInProgress = true;
2000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002001 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
2003
2004 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07002005 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002006 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002007 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
2008 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 return true;
2010 }
2011
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002012 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
2014 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002015 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002017 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 if (isPointerEvent) {
2019 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00002020
2021 if (mDragState &&
2022 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2023 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
2024 pilferPointersLocked(mDragState->dragWindow->getToken());
2025 }
2026
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002027 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002028 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002029 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
2030 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 } else {
2032 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002033 sp<WindowInfoHandle> focusedWindow =
2034 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
2035 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
2036 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002037 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
2038 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
2039 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002042 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 return false;
2044 }
2045
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002046 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002047 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002048 return true;
2049 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002050 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002051 CancelationOptions::Mode mode(
2052 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2053 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002054 CancelationOptions options(mode, "input event injection failed", entry->traceTracker);
Linnan Lid8150952024-01-26 18:07:17 +00002055 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002056 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 return true;
2058 }
2059
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002060 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002061 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002063 if (mTracer) {
2064 ensureEventTraced(*entry);
2065 for (const auto& target : inputTargets) {
2066 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2067 }
2068 }
2069
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 dispatchEventLocked(currentTime, entry, inputTargets);
2072 return true;
2073}
2074
chaviw98318de2021-05-19 16:45:23 -05002075void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002076 bool isExiting, const int32_t rawX,
2077 const int32_t rawY) {
2078 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002079 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002080 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2081 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002082
2083 enqueueInboundEventLocked(std::move(dragEntry));
2084}
2085
Prabir Pradhan24047542023-11-02 17:14:59 +00002086void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2087 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002088 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2089 if (connection == nullptr) {
2090 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002091 }
arthurhungb89ccb02020-12-30 16:19:01 +08002092 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002093 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002094}
2095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002096void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002097 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002098 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002099 "action=%s, actionButton=0x%x, flags=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002100 "metaState=0x%x, buttonState=0x%x, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002101 prefix, entry.eventTime, entry.deviceId,
Linnan Li13bf76a2024-05-05 19:18:02 +08002102 inputEventSourceToString(entry.source).c_str(), entry.displayId.toString().c_str(),
2103 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002104 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002106 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002107 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002108 "x=%f, y=%f, pressure=%f, size=%f, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07002109 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002110 i, entry.pointerProperties[i].id,
2111 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002112 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2113 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2114 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2115 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2116 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2117 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2118 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2119 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2120 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123}
2124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002125void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002126 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002129 if (DEBUG_DISPATCH_CYCLE) {
2130 ALOGD("dispatchEventToCurrentInputTargets");
2131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002133 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002134
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2136
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002137 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002139 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002140 std::shared_ptr<Connection> connection = inputTarget.connection;
2141 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 }
2143}
2144
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002145void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2147 // If the policy decides to close the app, we will get a channel removal event via
2148 // unregisterInputChannel, and will clean up the connection that way. We are already not
2149 // sending new pointers to the connection when it blocked, but focused events will continue to
2150 // pile up.
2151 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002152 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002153 if (connection->status != Connection::Status::NORMAL) {
2154 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002156 ScopedSyntheticEventTracer traceContext(mTracer);
Prabir Pradhanfc364722024-02-08 17:51:20 +00002157 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00002158 "application not responding", traceContext.getTracker());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002159
2160 sp<WindowInfoHandle> windowHandle;
2161 if (!connection->monitor) {
2162 windowHandle = getWindowHandleLocked(connection->getToken());
2163 if (windowHandle == nullptr) {
2164 // The window that is receiving this ANR was removed, so there is no need to generate
2165 // cancellations, because the cancellations would have already been generated when
2166 // the window was removed.
2167 return;
2168 }
2169 }
2170 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171}
2172
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002174 if (DEBUG_FOCUS) {
2175 ALOGD("Resetting ANR timeouts.");
2176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177
2178 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002180 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181}
2182
Tiger Huang721e26f2018-07-24 22:26:19 +08002183/**
2184 * Get the display id that the given event should go to. If this event specifies a valid display id,
2185 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2186 * Focused display is the display that the user most recently interacted with.
2187 */
Linnan Li13bf76a2024-05-05 19:18:02 +08002188ui::LogicalDisplayId InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002189 ui::LogicalDisplayId displayId{ui::LogicalDisplayId::INVALID};
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002191 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2193 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002194 break;
2195 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002196 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002197 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2198 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 break;
2200 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002201 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002202 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002203 case EventEntry::Type::FOCUS:
Chris Yef59a2f42020-10-16 12:55:26 -07002204 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002205 case EventEntry::Type::SENSOR:
2206 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002207 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002208 return ui::LogicalDisplayId::INVALID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002209 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002210 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002211 return displayId == ui::LogicalDisplayId::INVALID ? mFocusedDisplayId : displayId;
Tiger Huang721e26f2018-07-24 22:26:19 +08002212}
2213
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002214bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2215 const char* focusedWindowName) {
2216 if (mAnrTracker.empty()) {
2217 // already processed all events that we waited for
2218 mKeyIsWaitingForEventsTimeout = std::nullopt;
2219 return false;
2220 }
2221
2222 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2223 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002224 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002225 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002226 std::chrono::duration_cast<std::chrono::nanoseconds>(
2227 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002228 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 return true;
2230 }
2231
2232 // We still have pending events, and already started the timer
2233 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2234 return true; // Still waiting
2235 }
2236
2237 // Waited too long, and some connection still hasn't processed all motions
2238 // Just send the key to the focused window
2239 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2240 focusedWindowName);
2241 mKeyIsWaitingForEventsTimeout = std::nullopt;
2242 return false;
2243}
2244
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002245sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002246 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002247 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002248 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
Linnan Li13bf76a2024-05-05 19:18:02 +08002250 ui::LogicalDisplayId displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002251 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002252 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002253 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2254
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 // If there is no currently focused window and no focused application
2256 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002257 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2258 ALOGI("Dropping %s event because there is no focused window or focused application in "
Linnan Li13bf76a2024-05-05 19:18:02 +08002259 "display %s.",
2260 ftl::enum_string(entry.type).c_str(), displayId.toString().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 }
2263
Vishnu Nair062a8672021-09-03 16:07:44 -07002264 // Drop key events if requested by input feature
2265 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002266 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002267 }
2268
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2270 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2271 // start interacting with another application via touch (app switch). This code can be removed
2272 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2273 // an app is expected to have a focused window.
2274 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2275 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2276 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002277 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2278 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2279 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002280 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002281 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 ALOGW("Waiting because no window has focus but %s may eventually add a "
2283 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002284 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002285 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002286 outInjectionResult = InputEventInjectionResult::PENDING;
2287 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002288 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2289 // Already raised ANR. Drop the event
2290 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002291 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002292 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002293 } else {
2294 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = InputEventInjectionResult::PENDING;
2296 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002297 }
2298 }
2299
2300 // we have a valid, non-null focused window
2301 resetNoFocusedWindowTimeoutLocked();
2302
Prabir Pradhan5735a322022-04-11 17:23:34 +00002303 // Verify targeted injection.
2304 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2305 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002306 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2307 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002310 if (focusedWindowHandle->getInfo()->inputConfig.test(
2311 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002312 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002313 outInjectionResult = InputEventInjectionResult::PENDING;
2314 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002315 }
2316
2317 // If the event is a key event, then we must wait for all previous events to
2318 // complete before delivering it because previous events may have the
2319 // side-effect of transferring focus to a different window and we want to
2320 // ensure that the following keys are sent to the new window.
2321 //
2322 // Suppose the user touches a button in a window then immediately presses "A".
2323 // If the button causes a pop-up window to appear then we want to ensure that
2324 // the "A" key is delivered to the new pop-up window. This is because users
2325 // often anticipate pending UI changes when typing on a keyboard.
2326 // To obtain this behavior, we must serialize key events with respect to all
2327 // prior input events.
2328 if (entry.type == EventEntry::Type::KEY) {
2329 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002330 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002331 outInjectionResult = InputEventInjectionResult::PENDING;
2332 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002336 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2337 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338}
2339
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002340/**
2341 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2342 * that are currently unresponsive.
2343 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002344std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2345 const std::vector<Monitor>& monitors) const {
2346 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002347 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002348 [](const Monitor& monitor) REQUIRES(mLock) {
2349 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002350 if (!connection->responsive) {
2351 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002352 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002353 return false;
2354 }
2355 return true;
2356 });
2357 return responsiveMonitors;
2358}
2359
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002360std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002361 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002362 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002363 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002365 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 // For security reasons, we defer updating the touch state until we are sure that
2367 // event injection will be allowed.
Linnan Li13bf76a2024-05-05 19:18:02 +08002368 const ui::LogicalDisplayId displayId = entry.displayId;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002369 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002370 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
2372 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002373 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002375 // Copy current touch state into tempTouchState.
2376 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2377 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002378 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002379 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2381 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002382 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002383 }
2384
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002385 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386
2387 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2388 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2389 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002390 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2391 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002392 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002393 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2394 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002395 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2396 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2397 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002398 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002399
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002400 if (newGesture) {
2401 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002402 }
2403
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002404 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2405 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2406 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
2408
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002409 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002410 if (wasDown) {
2411 // Started hovering, but the device is already down: reject the hover event
2412 LOG(ERROR) << "Got hover event " << entry.getDescription()
2413 << " but the device is already down " << oldState->dump();
2414 outInjectionResult = InputEventInjectionResult::FAILED;
2415 return {};
2416 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002417 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2418 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002419 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002420 }
2421
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2423 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002424 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002425 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002426 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002427 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2428 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002429 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002430 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002431 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002432
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002433 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002434 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002437 if (newTouchedWindowHandle == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002438 ALOGD("No new touched window at (%.1f, %.1f) in display %s", x, y,
2439 displayId.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 // Try to assign the pointer to the first foreground window we find, if there is one.
Linnan Liccf6ce32024-04-11 20:32:13 +08002441 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Michael Wright3dd60e22019-03-27 22:06:44 +00002442 }
2443
Prabir Pradhan5735a322022-04-11 17:23:34 +00002444 // Verify targeted injection.
2445 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2446 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002447 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002448 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002449 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002450 }
2451
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002452 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002453 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2455 // New window supports splitting, but we should never split mouse events.
2456 isSplit = !isFromMouse;
2457 } else if (isSplit) {
2458 // New window does not support splitting but we have already split events.
2459 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002460 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2461 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002462 newTouchedWindowHandle = nullptr;
2463 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002464 } else {
2465 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002466 // be delivered to a new window which supports split touch. Pointers from a mouse device
2467 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002468 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002469 }
2470
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002471 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07002472 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus, entry.deviceId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002473 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002474 // Process the foreground window first so that it is the first to receive the event.
2475 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002476 }
2477
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002478 if (newTouchedWindows.empty()) {
Siarhei Vishniakouac42d242024-06-28 10:43:53 -07002479 LOG(INFO) << "Dropping event because there is no touchable window at (" << x << ", "
2480 << y << ") on display " << displayId << ": " << entry;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002481 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002482 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002483 }
2484
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002485 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002486 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002487 continue;
2488 }
2489
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002490 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002491 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002492 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002493 }
2494
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002495 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002496 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002497
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002498 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2499 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002500 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002501 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002502
2503 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002504 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002505 }
2506 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002507 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002508 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002509 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002510 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002511
2512 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002513
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002514 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002515 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2516 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Siarhei Vishniakoue535f972024-03-29 14:55:21 -07002517 Result<void> addResult =
2518 tempTouchState.addOrUpdateWindow(windowHandle,
2519 InputTarget::DispatchMode::AS_IS,
2520 targetFlags, entry.deviceId, {pointer},
2521 isDownOrPointerDown
2522 ? std::make_optional(
2523 entry.eventTime)
2524 : std::nullopt);
2525 if (!addResult.ok()) {
2526 LOG(ERROR) << "Error while processing " << entry << " for "
2527 << windowHandle->getName();
2528 logDispatchStateLocked();
2529 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002530 // If this is the pointer going down and the touched window has a wallpaper
2531 // then also add the touched wallpaper windows so they are locked in for the
2532 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2533 // SCROLL because the wallpaper engine only supports touch events. We would need to
2534 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2535 // handle these events.
2536 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002537 windowHandle->getInfo()->inputConfig.test(
2538 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2539 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2540 if (wallpaper != nullptr) {
2541 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2542 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002543 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002544 if (isSplit) {
2545 wallpaperFlags |= InputTarget::Flags::SPLIT;
2546 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002547 tempTouchState.addOrUpdateWindow(wallpaper,
2548 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002549 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002550 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002551 }
2552 }
2553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002555
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002556 // If a window is already pilfering some pointers, give it this new pointer as well and
2557 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2558 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002559 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002560 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002561 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002562 // This window is already pilfering some pointers, and this new pointer is also
2563 // going to it. Therefore, take over this pointer and don't give it to anyone
2564 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002565 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002566 }
2567 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002568
2569 // Restrict all pilfered pointers to the pilfering windows.
2570 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 } else {
2572 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2573
2574 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002575 if (!tempTouchState.isDown(entry.deviceId) &&
2576 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002577 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2578 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2579 << " is not down or we previously dropped the pointer down event in "
2580 << "display " << displayId << ": " << entry.getDescription();
2581 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002582 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002583 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 }
2585
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002586 // If the pointer is not currently hovering, then ignore the event.
2587 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2588 const int32_t pointerId = entry.pointerProperties[0].id;
2589 if (oldState == nullptr ||
2590 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2591 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2592 "display "
2593 << displayId << ": " << entry.getDescription();
2594 outInjectionResult = InputEventInjectionResult::FAILED;
2595 return {};
2596 }
2597 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2598 }
2599
arthurhung6d4bed92021-03-17 11:59:33 +08002600 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002601
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002603 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Linnan Li49b2b202024-04-12 12:46:40 +08002604 tempTouchState.isSlippery(entry.deviceId)) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002605 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002606 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002607 sp<WindowInfoHandle> oldTouchedWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002608 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002609 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002610 sp<WindowInfoHandle> newTouchedWindowHandle =
2611 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002612
Prabir Pradhan5735a322022-04-11 17:23:34 +00002613 // Verify targeted injection.
2614 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2615 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002616 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002617 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002618 }
2619
Linnan Libf069a32024-02-29 17:22:59 +00002620 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002621 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002622 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002623 newTouchedWindowHandle = nullptr;
2624 }
2625
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002626 if (newTouchedWindowHandle != nullptr &&
2627 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Linnan Li13bf76a2024-05-05 19:18:02 +08002628 ALOGI("Touch is slipping out of window %s into window %s in display %s",
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002629 oldTouchedWindowHandle->getName().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08002630 newTouchedWindowHandle->getName().c_str(), displayId.toString().c_str());
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002631
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002633 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002634 const PointerProperties& pointer = entry.pointerProperties[0];
2635 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002636
2637 const TouchedWindow& touchedWindow =
2638 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002639 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002640 InputTarget::DispatchMode::SLIPPERY_EXIT,
2641 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002642 touchedWindow.getDownTimeInTarget(entry.deviceId),
2643 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644
2645 // Make a slippery entrance into the new window.
2646 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002647 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002650 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002651 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002652 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002655 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
2657 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002658 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002659 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002660 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 }
2662
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002663 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2664 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002665 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002666 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002667
2668 // Check if the wallpaper window should deliver the corresponding event.
2669 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002670 tempTouchState, entry.deviceId, pointer, targets);
2671 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002672 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674 }
Arthur Hung96483742022-11-15 03:30:48 +00002675
2676 // Update the pointerIds for non-splittable when it received pointer down.
2677 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2678 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002679 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002680 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2681 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002682 // Ignore drag window for it should just track one pointer.
2683 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2684 continue;
2685 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002686 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002687 }
2688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 }
2690
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002691 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002692 {
2693 std::vector<TouchedWindow> hoveringWindows =
2694 getHoveringWindowsLocked(oldState, tempTouchState, entry);
Linnan Li41859c42024-03-05 16:20:34 +00002695 // Hardcode to single hovering pointer for now.
2696 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2697 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002698 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002699 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2700 touchedWindow.targetFlags, pointerIds,
2701 touchedWindow.getDownTimeInTarget(entry.deviceId),
2702 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
Prabir Pradhan5735a322022-04-11 17:23:34 +00002706 // Ensure that all touched windows are valid for injection.
2707 if (entry.injectionState != nullptr) {
2708 std::string errs;
2709 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002710 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2711 if (err) errs += "\n - " + *err;
2712 }
2713 if (!errs.empty()) {
2714 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002715 "%s:%s",
2716 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002717 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002718 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002719 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002720 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002721
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002722 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2723 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002725 sp<WindowInfoHandle> foregroundWindowHandle =
Linnan Liccf6ce32024-04-11 20:32:13 +08002726 tempTouchState.getFirstForegroundWindowHandle(entry.deviceId);
Michael Wright3dd60e22019-03-27 22:06:44 +00002727 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002728 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002729 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002730 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002731 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002732 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002733 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2734 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737 }
2738 }
2739 }
2740
Harry Cuttsb166c002023-05-09 13:06:05 +00002741 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2742 // only want the system UI to handle these gestures.
2743 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2744 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2745 if (isTouchpadNavGesture) {
2746 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2747 }
2748
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002749 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002750 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002751 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002752 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002753 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002754 continue;
2755 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002756 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002757 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002758 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002759 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002760
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002761 // During targeted injection, only allow owned targets to receive events
2762 std::erase_if(targets, [&](const InputTarget& target) {
2763 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2764 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2765 if (err) {
2766 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2767 << ": " << (*err);
2768 return true;
2769 }
2770 return false;
2771 });
2772
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002773 if (targets.empty()) {
2774 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2775 outInjectionResult = InputEventInjectionResult::FAILED;
2776 return {};
2777 }
2778
2779 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2780 // window that is actually receiving the entire gesture.
2781 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002782 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002783 })) {
2784 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2785 << entry.getDescription();
2786 outInjectionResult = InputEventInjectionResult::FAILED;
2787 return {};
2788 }
2789
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002790 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791
Prabir Pradhan502a7252023-12-01 16:11:24 +00002792 // Now that we have generated all of the input targets for this event, reset the dispatch
2793 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002794 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002795 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002796 }
2797
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002798 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002799 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002800 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002801 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002802 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002803 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002804 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002805 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2806 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002807 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2808 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2809 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002812 // Save changes unless the action was scroll in which case the temporary touch
2813 // state was only valid for this one action.
2814 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002815 if (displayId >= ui::LogicalDisplayId::DEFAULT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002816 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002817 mTouchStatesByDisplay[displayId] = tempTouchState;
2818 } else {
2819 mTouchStatesByDisplay.erase(displayId);
2820 }
2821 }
2822
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002823 if (tempTouchState.windows.empty()) {
2824 mTouchStatesByDisplay.erase(displayId);
2825 }
2826
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002827 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828}
2829
Linnan Li13bf76a2024-05-05 19:18:02 +08002830void InputDispatcher::finishDragAndDrop(ui::LogicalDisplayId displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002831 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2832 // have an explicit reason to support it.
2833 constexpr bool isStylus = false;
2834
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002835 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002836 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002837 if (dropWindow) {
2838 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002839 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002840 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002841 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002842 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002843 }
2844 mDragState.reset();
2845}
2846
2847void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002848 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002849 return;
2850 }
2851
arthurhung6d4bed92021-03-17 11:59:33 +08002852 if (!mDragState->isStartDrag) {
2853 mDragState->isStartDrag = true;
2854 mDragState->isStylusButtonDownAtStart =
2855 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2856 }
2857
Arthur Hung54745652022-04-20 07:17:41 +00002858 // Find the pointer index by id.
2859 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002860 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002861 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2862 if (pointerProperties.id == mDragState->pointerId) {
2863 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002864 }
Arthur Hung54745652022-04-20 07:17:41 +00002865 }
arthurhung6d4bed92021-03-17 11:59:33 +08002866
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002867 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002868 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002869 }
2870
2871 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2872 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2873 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2874
2875 switch (maskedAction) {
2876 case AMOTION_EVENT_ACTION_MOVE: {
2877 // Handle the special case : stylus button no longer pressed.
2878 bool isStylusButtonDown =
2879 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2880 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2881 finishDragAndDrop(entry.displayId, x, y);
2882 return;
2883 }
2884
2885 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2886 // until we have an explicit reason to support it.
2887 constexpr bool isStylus = false;
2888
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002889 sp<WindowInfoHandle> hoverWindowHandle =
2890 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2891 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002892 // enqueue drag exit if needed.
2893 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2894 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2895 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002896 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002897 y);
2898 }
2899 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2900 }
2901 // enqueue drag location if needed.
2902 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002903 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002904 }
2905 break;
2906 }
2907
2908 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002909 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002910 break;
2911 }
2912 // The drag pointer is up.
2913 [[fallthrough]];
2914 case AMOTION_EVENT_ACTION_UP:
2915 finishDragAndDrop(entry.displayId, x, y);
2916 break;
2917 case AMOTION_EVENT_ACTION_CANCEL: {
2918 ALOGD("Receiving cancel when drag and drop.");
2919 sendDropWindowCommandLocked(nullptr, 0, 0);
2920 mDragState.reset();
2921 break;
2922 }
arthurhungb89ccb02020-12-30 16:19:01 +08002923 }
2924}
2925
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002926std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2927 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002928 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002929 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002930 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2931 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002932 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2933 return {};
2934 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002935 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002936 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002937 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002938 inputTarget.flags = targetFlags;
2939 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2940 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2941 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2942 if (displayInfoIt != mDisplayInfos.end()) {
2943 inputTarget.displayTransform = displayInfoIt->second.transform;
2944 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002945 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002946 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2947 }
2948 return inputTarget;
2949}
2950
chaviw98318de2021-05-19 16:45:23 -05002951void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002952 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002953 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002954 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002955 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002956 std::vector<InputTarget>::iterator it =
2957 std::find_if(inputTargets.begin(), inputTargets.end(),
2958 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002959 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002960 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002961
chaviw98318de2021-05-19 16:45:23 -05002962 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002963
2964 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002965 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002966 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2967 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002968 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002969 return;
2970 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002971 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002972 it = inputTargets.end() - 1;
2973 }
2974
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002975 if (it->flags != targetFlags) {
2976 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2977 }
2978 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2979 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2980 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2981 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002982}
2983
2984void InputDispatcher::addPointerWindowTargetLocked(
2985 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002986 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2987 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2988 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002989 if (pointerIds.none()) {
2990 for (const auto& target : inputTargets) {
2991 LOG(INFO) << "Target: " << target;
2992 }
2993 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2994 return;
2995 }
2996 std::vector<InputTarget>::iterator it =
2997 std::find_if(inputTargets.begin(), inputTargets.end(),
2998 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002999 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003000 });
3001
3002 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
3003 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
3004 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
3005 // input targets for hovering pointers and for touching pointers.
3006 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
3007 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003008 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003009 // Force the code below to create a new input target
3010 it = inputTargets.end();
3011 }
3012
3013 const WindowInfo* windowInfo = windowHandle->getInfo();
3014
3015 if (it == inputTargets.end()) {
3016 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003017 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
3018 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003019 if (!target) {
3020 return;
3021 }
3022 inputTargets.push_back(*target);
3023 it = inputTargets.end() - 1;
3024 }
3025
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003026 if (it->dispatchMode != dispatchMode) {
3027 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
3028 << ftl::enum_string(dispatchMode) << ", it=" << *it;
3029 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003030 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003031 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
3032 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07003033 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003034 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003035 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07003036 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
3037 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003038
Siarhei Vishniakou59967592024-04-01 16:17:46 -07003039 Result<void> result = it->addPointers(pointerIds, windowInfo->transform);
3040 if (!result.ok()) {
3041 logDispatchStateLocked();
3042 LOG(FATAL) << result.error().message();
3043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044}
3045
Michael Wright3dd60e22019-03-27 22:06:44 +00003046void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Linnan Li13bf76a2024-05-05 19:18:02 +08003047 ui::LogicalDisplayId displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003048 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3049 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003050
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003051 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003052 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003053 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3054 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003055 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3056 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003057 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003058 target.setDefaultPointerTransform(target.displayTransform);
3059 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060 }
3061}
3062
Robert Carrc9bf1d32020-04-13 17:21:08 -07003063/**
3064 * Indicate whether one window handle should be considered as obscuring
3065 * another window handle. We only check a few preconditions. Actually
3066 * checking the bounds is left to the caller.
3067 */
chaviw98318de2021-05-19 16:45:23 -05003068static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3069 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003070 // Compare by token so cloned layers aren't counted
3071 if (haveSameToken(windowHandle, otherHandle)) {
3072 return false;
3073 }
3074 auto info = windowHandle->getInfo();
3075 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003076 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003077 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003078 } else if (otherInfo->alpha == 0 &&
3079 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003080 // Those act as if they were invisible, so we don't need to flag them.
3081 // We do want to potentially flag touchable windows even if they have 0
3082 // opacity, since they can consume touches and alter the effects of the
3083 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003084 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003085 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3086 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003087 } else if (info->ownerUid == otherInfo->ownerUid) {
3088 // If ownerUid is the same we don't generate occlusion events as there
3089 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003090 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003091 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003092 return false;
3093 } else if (otherInfo->displayId != info->displayId) {
3094 return false;
3095 }
3096 return true;
3097}
3098
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003099/**
3100 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3101 * untrusted, one should check:
3102 *
3103 * 1. If result.hasBlockingOcclusion is true.
3104 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3105 * BLOCK_UNTRUSTED.
3106 *
3107 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3108 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3109 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3110 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3111 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3112 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3113 *
3114 * If neither of those is true, then it means the touch can be allowed.
3115 */
3116InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
Linnan Li5e5645e2024-03-05 14:43:05 +00003117 const sp<WindowInfoHandle>& windowHandle, float x, float y) const {
chaviw98318de2021-05-19 16:45:23 -05003118 const WindowInfo* windowInfo = windowHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003119 ui::LogicalDisplayId displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003120 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003121 TouchOcclusionInfo info;
3122 info.hasBlockingOcclusion = false;
3123 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003124 info.obscuringUid = gui::Uid::INVALID;
3125 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003126 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003127 if (windowHandle == otherHandle) {
3128 break; // All future windows are below us. Exit early.
3129 }
chaviw98318de2021-05-19 16:45:23 -05003130 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li5e5645e2024-03-05 14:43:05 +00003131 if (canBeObscuredBy(windowHandle, otherHandle) &&
3132 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId)) &&
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003133 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003134 if (DEBUG_TOUCH_OCCLUSION) {
3135 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003136 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003137 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003138 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3139 // we perform the checks below to see if the touch can be propagated or not based on the
3140 // window's touch occlusion mode
3141 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3142 info.hasBlockingOcclusion = true;
3143 info.obscuringUid = otherInfo->ownerUid;
3144 info.obscuringPackage = otherInfo->packageName;
3145 break;
3146 }
3147 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003148 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003149 float opacity =
3150 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3151 // Given windows A and B:
3152 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3153 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3154 opacityByUid[uid] = opacity;
3155 if (opacity > info.obscuringOpacity) {
3156 info.obscuringOpacity = opacity;
3157 info.obscuringUid = uid;
3158 info.obscuringPackage = otherInfo->packageName;
3159 }
3160 }
3161 }
3162 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003163 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003164 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003165 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003166 return info;
3167}
3168
chaviw98318de2021-05-19 16:45:23 -05003169std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003170 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003171 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003172 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3173 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3174 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003175 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003176 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003177 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3178 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003179 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3180 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3181 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003182 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003183}
3184
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003185bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3186 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003187 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3188 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003189 return false;
3190 }
3191 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003192 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003193 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003194 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003195 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3196 return false;
3197 }
3198 return true;
3199}
3200
chaviw98318de2021-05-19 16:45:23 -05003201bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Linnan Li5e5645e2024-03-05 14:43:05 +00003202 float x, float y) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003203 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003204 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3205 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003206 if (windowHandle == otherHandle) {
3207 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 }
chaviw98318de2021-05-19 16:45:23 -05003209 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003210 if (canBeObscuredBy(windowHandle, otherHandle) &&
Linnan Li5e5645e2024-03-05 14:43:05 +00003211 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 return true;
3213 }
3214 }
3215 return false;
3216}
3217
chaviw98318de2021-05-19 16:45:23 -05003218bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08003219 ui::LogicalDisplayId displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003220 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3221 const WindowInfo* windowInfo = windowHandle->getInfo();
3222 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003223 if (windowHandle == otherHandle) {
3224 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003225 }
chaviw98318de2021-05-19 16:45:23 -05003226 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li13bf76a2024-05-05 19:18:02 +08003227 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003228 return true;
3229 }
3230 }
3231 return false;
3232}
3233
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003234std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003235 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003236 if (applicationHandle != nullptr) {
3237 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003238 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 } else {
3240 return applicationHandle->getName();
3241 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003242 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003243 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003245 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247}
3248
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003249void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003250 if (!isUserActivityEvent(eventEntry)) {
3251 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003252 return;
3253 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003254
3255 const int32_t eventType = getUserActivityEventType(eventEntry);
3256 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3257 // Note that we're directly getting the time diff between the current event and the previous
3258 // event. This is assuming that the first user event always happens at a timestamp that is
3259 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3260 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3261 // value than the potential first user activity event time, so this is ok.
3262 std::chrono::nanoseconds timeSinceLastEvent =
3263 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3264 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3265 return;
3266 }
3267 }
3268
Linnan Li13bf76a2024-05-05 19:18:02 +08003269 ui::LogicalDisplayId displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003270 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003271 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003272 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003273 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003274 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003275 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 }
3277 }
3278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003279 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003280 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003281 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3282 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 return;
3284 }
Josep del Riob3981622023-04-18 15:49:45 +00003285 if (windowDisablingUserActivityInfo != nullptr) {
3286 if (DEBUG_DISPATCH_CYCLE) {
3287 ALOGD("Not poking user activity: disabled by window '%s'.",
3288 windowDisablingUserActivityInfo->name.c_str());
3289 }
3290 return;
3291 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003294 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003295 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3296 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 return;
3298 }
Josep del Riob3981622023-04-18 15:49:45 +00003299 // Don't inhibit events that were intercepted or are not passed to
3300 // the apps, like system shortcuts
3301 if (windowDisablingUserActivityInfo != nullptr &&
Josep del Rioc8fdedb2024-05-21 13:32:43 +00003302 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP) {
Josep del Riob3981622023-04-18 15:49:45 +00003303 if (DEBUG_DISPATCH_CYCLE) {
3304 ALOGD("Not poking user activity: disabled by window '%s'.",
3305 windowDisablingUserActivityInfo->name.c_str());
3306 }
3307 return;
3308 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003311 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003313 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003314 break;
3315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
3317
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003318 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003319 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3320 REQUIRES(mLock) {
3321 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003322 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003323 };
3324 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325}
3326
3327void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003328 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003329 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003330 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003331 ATRACE_NAME_IF(ATRACE_ENABLED(),
3332 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3333 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003334 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003335 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003336 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003337 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003338 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003339 inputTarget.getPointerInfoString().c_str());
3340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341
3342 // Skip this event if the connection status is not normal.
3343 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003344 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003345 if (DEBUG_DISPATCH_CYCLE) {
3346 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003347 connection->getInputChannelName().c_str(),
3348 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 return;
3351 }
3352
3353 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003354 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003355 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003356 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003357 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003359 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003360 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003361 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3362 logDispatchStateLocked();
3363 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3364 "target on connection "
3365 << connection->getInputChannelName() << " for "
3366 << originalMotionEntry.getDescription();
3367 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003368 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003369 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003370 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 if (!splitMotionEntry) {
3372 return; // split event was dropped
3373 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003374 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3375 std::string reason = std::string("reason=pointer cancel on split window");
3376 android_log_event_list(LOGTAG_INPUT_CANCEL)
3377 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3378 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003379 if (DEBUG_FOCUS) {
3380 ALOGD("channel '%s' ~ Split motion event.",
3381 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003382 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003383 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003384 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3385 std::move(splitMotionEntry),
3386 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 return;
3388 }
3389 }
3390
3391 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003392 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3393 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394}
3395
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003396void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3397 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3398 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003399 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003400 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3401 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003402 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003403
hongzuo liu95785e22022-09-06 02:51:35 +00003404 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003406 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
3408 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003409 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 startDispatchCycleLocked(currentTime, connection);
3411 }
3412}
3413
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003414void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003415 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003416 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003417 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3418 eventEntry->type == EventEntry::Type::MOTION;
3419 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3420 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3421 << inputTarget << " connection: " << connection->getInputChannelName()
3422 << " entry: " << eventEntry->getDescription();
3423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 // This is a new event.
3425 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003426 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003427 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
Prabir Pradhana67623c2024-02-21 06:57:36 +00003428 mWindowInfosVsyncId, mTracer.get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003430 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3431 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003432 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003434 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003435 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003436 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3437 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003438 LOG(WARNING) << "channel " << connection->getInputChannelName()
3439 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003440 return; // skip the inconsistent event
3441 }
3442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003445 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003446 std::shared_ptr<const MotionEntry> resolvedMotion =
3447 std::static_pointer_cast<const MotionEntry>(eventEntry);
3448 {
3449 // Determine the resolved motion entry.
3450 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3451 int32_t resolvedAction = motionEntry.action;
3452 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003454 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003455 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003456 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003457 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003458 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003459 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003460 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003461 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003462 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003463 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3464 }
3465 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3466 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3467 motionEntry.displayId)) {
3468 if (DEBUG_DISPATCH_CYCLE) {
3469 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3470 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3471 "enter event";
3472 }
3473 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3474 }
3475
3476 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3477 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3478 }
3479 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3480 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3481 }
3482 if (dispatchEntry->targetFlags.test(
3483 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3484 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3485 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003486 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3487 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3488 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003489
3490 dispatchEntry->resolvedFlags = resolvedFlags;
3491 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003492 std::optional<std::vector<PointerProperties>> usingProperties;
3493 std::optional<std::vector<PointerCoords>> usingCoords;
3494 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3495 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3496 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3497 // the dispatcher, and therefore the coordinates of this event are currently
3498 // incorrect. These events should use the coordinates of the last dispatched
3499 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3500 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3501 std::optional<std::pair<std::vector<PointerProperties>,
3502 std::vector<PointerCoords>>>
3503 pointerInfo =
3504 connection->inputState.getPointersOfLastEvent(motionEntry,
3505 hovering);
3506 if (pointerInfo) {
3507 usingProperties = pointerInfo->first;
3508 usingCoords = pointerInfo->second;
3509 }
3510 }
Prabir Pradhana67623c2024-02-21 06:57:36 +00003511 {
3512 // Generate a new MotionEntry with a new eventId using the resolved action
3513 // and flags, and set it as the resolved entry.
3514 auto newEntry = std::make_shared<
3515 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3516 motionEntry.eventTime, motionEntry.deviceId,
3517 motionEntry.source, motionEntry.displayId,
3518 motionEntry.policyFlags, resolvedAction,
3519 motionEntry.actionButton, resolvedFlags,
3520 motionEntry.metaState, motionEntry.buttonState,
3521 motionEntry.classification, motionEntry.edgeFlags,
3522 motionEntry.xPrecision, motionEntry.yPrecision,
3523 motionEntry.xCursorPosition,
3524 motionEntry.yCursorPosition, motionEntry.downTime,
3525 usingProperties.value_or(
3526 motionEntry.pointerProperties),
3527 usingCoords.value_or(motionEntry.pointerCoords));
3528 if (mTracer) {
3529 ensureEventTraced(motionEntry);
3530 newEntry->traceTracker =
3531 mTracer->traceDerivedEvent(*newEntry,
3532 *motionEntry.traceTracker);
3533 }
3534 resolvedMotion = newEntry;
3535 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003536 if (ATRACE_ENABLED()) {
3537 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3538 ") to MotionEvent(id=0x%" PRIx32 ").",
3539 motionEntry.id, resolvedMotion->id);
3540 ATRACE_NAME(message.c_str());
3541 }
3542
3543 // Set the resolved motion entry in the DispatchEntry.
3544 dispatchEntry->eventEntry = resolvedMotion;
3545 eventEntry = resolvedMotion;
3546 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003549 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3550 // devices being active at the same time in the same window, so if a new device is
3551 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003552 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003553 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003554 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003555 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003556 << connection->getInputChannelName() << " with event "
3557 << cancelEvent->getDescription();
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003558 if (mTracer) {
3559 static_cast<MotionEntry&>(*cancelEvent).traceTracker =
3560 mTracer->traceDerivedEvent(*cancelEvent, *resolvedMotion->traceTracker);
3561 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003562 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003563 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhana67623c2024-02-21 06:57:36 +00003564 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId,
3565 mTracer.get());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003566
3567 // Send these cancel events to the queue before sending the event from the new
3568 // device.
3569 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3570 }
3571
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003572 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003573 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003574 LOG(WARNING) << "channel " << connection->getInputChannelName()
3575 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 return; // skip the inconsistent event
3577 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003578 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003579 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003580 // Skip reporting pointer down outside focus to the policy.
3581 break;
3582 }
3583
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003584 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003585 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003586
3587 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003589 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003590 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003591 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3592 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003593 break;
3594 }
Chris Yef59a2f42020-10-16 12:55:26 -07003595 case EventEntry::Type::SENSOR: {
3596 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3597 break;
3598 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003599 case EventEntry::Type::DEVICE_RESET: {
3600 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003601 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003602 break;
3603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605
3606 // Remember that we are waiting for this dispatch to complete.
3607 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003608 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610
3611 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003612 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003613 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003614}
3615
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003616/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003617 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003618 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003619 * The first role is to log input interaction with windows, which helps determine what the user was
3620 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3621 * that user started interacting with launcher window, as well as any other window that received
3622 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3623 * when the set of tokens that received the event changes. It is not logged again as long as the
3624 * user is interacting with the same windows.
3625 *
3626 * The second role is to track input device activity for metrics collection. For each input event,
3627 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3628 * input_interaction logs, the device interaction is reported even when the set of interaction
3629 * tokens do not change.
3630 *
3631 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3632 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003633 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003634void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3635 const std::vector<InputTarget>& targets) {
3636 int32_t deviceId;
3637 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003638 // Skip ACTION_UP events, and all events other than keys and motions
3639 if (entry.type == EventEntry::Type::KEY) {
3640 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3641 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3642 return;
3643 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003644 deviceId = keyEntry.deviceId;
3645 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003646 } else if (entry.type == EventEntry::Type::MOTION) {
3647 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3648 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003649 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3650 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003651 return;
3652 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003653 deviceId = motionEntry.deviceId;
3654 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003655 } else {
3656 return; // Not a key or a motion
3657 }
3658
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003659 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003660 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003661 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003662 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003663 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003664 continue; // Skip windows that receive ACTION_OUTSIDE
3665 }
3666
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003667 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003668 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003669 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003670 if (target.windowHandle) {
3671 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3672 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003673 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003674
3675 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3676 REQUIRES(mLock) {
3677 scoped_unlock unlock(mLock);
3678 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3679 };
3680 postCommandLocked(std::move(command));
3681
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003682 if (newConnectionTokens == mInteractionConnectionTokens) {
3683 return; // no change
3684 }
3685 mInteractionConnectionTokens = newConnectionTokens;
3686
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003687 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003688 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003689 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003690 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003691 std::string message = "Interaction with: " + targetList;
3692 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003693 message += "<none>";
3694 }
3695 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3696}
3697
chaviwfd6d3512019-03-25 13:23:49 -07003698void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003699 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003700 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003701 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3702 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003703 return;
3704 }
3705
Vishnu Nairc519ff72021-01-21 08:23:08 -08003706 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003707 if (focusedToken == token) {
3708 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003709 return;
3710 }
3711
Prabir Pradhancef936d2021-07-21 16:17:52 +00003712 auto command = [this, token]() REQUIRES(mLock) {
3713 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003714 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003715 };
3716 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717}
3718
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003719status_t InputDispatcher::publishMotionEvent(Connection& connection,
3720 DispatchEntry& dispatchEntry) const {
3721 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3722 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3723
3724 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003725 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003726
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003727 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003728 // Set the X and Y offset and X and Y scale depending on the input source.
3729 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003730 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003731 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3732 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003733 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003734 scaledCoords[i] = motionEntry.pointerCoords[i];
3735 // Don't apply window scale here since we don't want scale to affect raw
3736 // coordinates. The scale will be sent back to the client and applied
3737 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003738 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003739 }
3740 usingCoords = scaledCoords;
3741 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003742 }
3743
3744 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3745
3746 // Publish the motion event.
3747 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003748 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3749 motionEntry.source, motionEntry.displayId, std::move(hmac),
3750 motionEntry.action, motionEntry.actionButton,
3751 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3752 motionEntry.metaState, motionEntry.buttonState,
3753 motionEntry.classification, dispatchEntry.transform,
3754 motionEntry.xPrecision, motionEntry.yPrecision,
3755 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3756 dispatchEntry.rawTransform, motionEntry.downTime,
3757 motionEntry.eventTime, motionEntry.getPointerCount(),
3758 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003759}
3760
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003762 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003763 ATRACE_NAME_IF(ATRACE_ENABLED(),
3764 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3765 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003766 if (DEBUG_DISPATCH_CYCLE) {
3767 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003770 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003771 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003773 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003774 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775
3776 // Publish the event.
3777 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003778 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3779 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003780 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003781 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3782 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003783 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003784 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3785 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003789 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003790 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3791 keyEntry.deviceId, keyEntry.source,
3792 keyEntry.displayId, std::move(hmac),
3793 keyEntry.action, dispatchEntry->resolvedFlags,
3794 keyEntry.keyCode, keyEntry.scanCode,
3795 keyEntry.metaState, keyEntry.repeatCount,
3796 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003797 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003798 ensureEventTraced(keyEntry);
3799 mTracer->traceEventDispatch(*dispatchEntry, *keyEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003800 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 }
3803
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003804 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003805 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003806 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3807 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003808 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003809 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003810 status = publishMotionEvent(*connection, *dispatchEntry);
Siarhei Vishniakoub0058742024-07-01 16:42:49 -07003811 if (status == BAD_VALUE) {
3812 logDispatchStateLocked();
3813 LOG(FATAL) << "Publisher failed for " << motionEntry;
3814 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003815 if (mTracer) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00003816 ensureEventTraced(motionEntry);
3817 mTracer->traceEventDispatch(*dispatchEntry, *motionEntry.traceTracker);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003818 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 break;
3820 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003821
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003822 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003823 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003824 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003825 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003826 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003827 break;
3828 }
3829
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003830 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3831 const TouchModeEntry& touchModeEntry =
3832 static_cast<const TouchModeEntry&>(eventEntry);
3833 status = connection->inputPublisher
3834 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3835 touchModeEntry.inTouchMode);
3836
3837 break;
3838 }
3839
Prabir Pradhan99987712020-11-10 18:43:05 -08003840 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3841 const auto& captureEntry =
3842 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
Hiroki Sato25040232024-02-22 17:21:22 +09003843 status =
3844 connection->inputPublisher
3845 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3846 captureEntry.pointerCaptureRequest.isEnable());
Prabir Pradhan99987712020-11-10 18:43:05 -08003847 break;
3848 }
3849
arthurhungb89ccb02020-12-30 16:19:01 +08003850 case EventEntry::Type::DRAG: {
3851 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3852 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3853 dragEntry.id, dragEntry.x,
3854 dragEntry.y,
3855 dragEntry.isExiting);
3856 break;
3857 }
3858
Chris Yef59a2f42020-10-16 12:55:26 -07003859 case EventEntry::Type::DEVICE_RESET:
3860 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003861 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003862 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003863 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 }
3866
3867 // Check the result.
3868 if (status) {
3869 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003870 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 "This is unexpected because the wait queue is empty, so the pipe "
3873 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003874 "event to it, status=%s(%d)",
3875 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3876 status);
Harry Cutts33476232023-01-30 19:57:29 +00003877 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 } else {
3879 // Pipe is full and we are waiting for the app to finish process some events
3880 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003881 if (DEBUG_DISPATCH_CYCLE) {
3882 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3883 "waiting for the application to catch up",
3884 connection->getInputChannelName().c_str());
3885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 }
3887 } else {
3888 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003889 "status=%s(%d)",
3890 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3891 status);
Harry Cutts33476232023-01-30 19:57:29 +00003892 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 }
3894 return;
3895 }
3896
3897 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003898 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3899 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3900 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003901 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003902 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003903 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003904 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003905 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 }
3907}
3908
chaviw09c8d2d2020-08-24 15:48:26 -07003909std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3910 size_t size;
3911 switch (event.type) {
3912 case VerifiedInputEvent::Type::KEY: {
3913 size = sizeof(VerifiedKeyEvent);
3914 break;
3915 }
3916 case VerifiedInputEvent::Type::MOTION: {
3917 size = sizeof(VerifiedMotionEvent);
3918 break;
3919 }
3920 }
3921 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3922 return mHmacKeyManager.sign(start, size);
3923}
3924
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003925const std::array<uint8_t, 32> InputDispatcher::getSignature(
3926 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003927 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003928 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003929 // Only sign events up and down events as the purely move events
3930 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003931 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003932 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003933
3934 VerifiedMotionEvent verifiedEvent =
3935 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3936 verifiedEvent.actionMasked = actionMasked;
3937 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3938 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003939}
3940
3941const std::array<uint8_t, 32> InputDispatcher::getSignature(
3942 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3943 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3944 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003945 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003946}
3947
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003949 const std::shared_ptr<Connection>& connection,
3950 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003951 if (DEBUG_DISPATCH_CYCLE) {
3952 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3953 connection->getInputChannelName().c_str(), seq, toString(handled));
3954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003956 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 return;
3958 }
3959
3960 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003961 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3962 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3963 };
3964 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965}
3966
3967void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003968 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003969 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003970 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003971 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3972 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
3975 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003976 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003977 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003978 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003979 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
3981 // The connection appears to be unrecoverably broken.
3982 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003983 if (connection->status == Connection::Status::NORMAL) {
3984 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 if (notify) {
3987 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003988 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3989 connection->getInputChannelName().c_str());
3990
3991 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003992 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003993 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003994 };
3995 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997 }
3998}
3999
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004000void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004001 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004002 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004003 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 }
4005}
4006
Prabir Pradhan8c90d782023-09-15 21:16:44 +00004007void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004009 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011}
4012
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004013int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
4014 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004015 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004016 if (connection == nullptr) {
4017 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
4018 connectionToken.get(), events);
4019 return 0; // remove the callback
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004022 bool notify;
4023 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
4024 if (!(events & ALOOPER_EVENT_INPUT)) {
4025 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
4026 "events=0x%x",
4027 connection->getInputChannelName().c_str(), events);
4028 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 }
4030
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004031 nsecs_t currentTime = now();
4032 bool gotOne = false;
4033 status_t status = OK;
4034 for (;;) {
4035 Result<InputPublisher::ConsumerResponse> result =
4036 connection->inputPublisher.receiveConsumerResponse();
4037 if (!result.ok()) {
4038 status = result.error().code();
4039 break;
4040 }
4041
4042 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
4043 const InputPublisher::Finished& finish =
4044 std::get<InputPublisher::Finished>(*result);
4045 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
4046 finish.consumeTime);
4047 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004048 if (shouldReportMetricsForConnection(*connection)) {
4049 const InputPublisher::Timeline& timeline =
4050 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004051 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
4052 connection->getToken(),
4053 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00004054 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004055 }
4056 gotOne = true;
4057 }
4058 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004059 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004060 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 return 1;
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 }
4064
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004065 notify = status != DEAD_OBJECT || !connection->monitor;
4066 if (notify) {
4067 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4068 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4069 status);
4070 }
4071 } else {
4072 // Monitor channels are never explicitly unregistered.
4073 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004074 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004075 notify = !connection->monitor && stillHaveWindowHandle;
4076 if (notify) {
4077 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4078 connection->getInputChannelName().c_str(), events);
4079 }
4080 }
4081
4082 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004083 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004084 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085}
4086
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004089 // Cancel windows (i.e. non-monitors).
4090 // A channel must have at least one window to receive any input. If a window was removed, the
4091 // event streams directed to the window will already have been canceled during window removal.
4092 // So there is no need to generate cancellations for connections without any windows.
4093 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4094 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4095 // through a non-touched window if there are more than one window for an input channel.
4096 if (cancelPointers) {
4097 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4098 if (options.displayId.has_value() && options.displayId != displayId) {
4099 continue;
4100 }
4101 for (const auto& touchedWindow : touchState.windows) {
4102 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4103 }
4104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004106 // Follow up by generating cancellations for all windows, because we don't explicitly track
4107 // the windows that have an ongoing focus event stream.
4108 if (cancelNonPointers) {
4109 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4110 for (const auto& windowHandle : handles) {
4111 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4112 }
4113 }
4114 }
4115
4116 // Cancel monitors.
4117 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118}
4119
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004121 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004122 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004123 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004124 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4125 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004126 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004127 }
4128}
4129
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004130void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4131 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4132 const std::shared_ptr<Connection>& connection) {
4133 if (windowHandle == nullptr) {
4134 LOG(FATAL) << __func__ << ": Window handle must not be null";
4135 }
4136 if (connection) {
4137 // The connection can be optionally provided to avoid multiple lookups.
4138 if (windowHandle->getToken() != connection->getToken()) {
4139 LOG(FATAL) << __func__
4140 << ": Wrong connection provided for window: " << windowHandle->getName();
4141 }
4142 }
4143
4144 std::shared_ptr<Connection> resolvedConnection =
4145 connection ? connection : getConnectionLocked(windowHandle->getToken());
4146 if (!resolvedConnection) {
4147 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4148 return;
4149 }
4150 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4151}
4152
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004154 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4155 const sp<WindowInfoHandle>& window) {
4156 if (!connection->monitor && window == nullptr) {
4157 LOG(FATAL) << __func__
4158 << ": Cannot send event to non-monitor channel without a window - channel: "
4159 << connection->getInputChannelName();
4160 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004161 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 return;
4163 }
4164
4165 nsecs_t currentTime = now();
4166
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004167 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004168 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004170 if (cancelationEvents.empty()) {
4171 return;
4172 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004173
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004174 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4175 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004176 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004177 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004178 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004179 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004180
Arthur Hungb3307ee2021-10-14 10:57:37 +00004181 std::string reason = std::string("reason=").append(options.reason);
4182 android_log_event_list(LOGTAG_INPUT_CANCEL)
4183 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4184
hongzuo liu95785e22022-09-06 02:51:35 +00004185 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004186 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004187 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004188 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004189
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004190 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004191 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004192 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004193
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004194 switch (cancelationEventEntry->type) {
4195 case EventEntry::Type::KEY: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004196 if (mTracer) {
4197 static_cast<KeyEntry&>(*cancelationEventEntry).traceTracker =
4198 mTracer->traceDerivedEvent(*cancelationEventEntry,
4199 *options.traceTracker);
4200 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004201 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004202 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004203 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4204 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004205 } else {
4206 targets.emplace_back(fallbackTarget);
4207 }
4208 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004209 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004211 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004212 if (mTracer) {
4213 static_cast<MotionEntry&>(*cancelationEventEntry).traceTracker =
4214 mTracer->traceDerivedEvent(*cancelationEventEntry,
4215 *options.traceTracker);
4216 }
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004217 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004218 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004219 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004220 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004221 pointerIndex++) {
4222 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4223 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004224 if (mDragState && mDragState->dragWindow->getToken() == token &&
4225 pointerIds.test(mDragState->pointerId)) {
4226 LOG(INFO) << __func__
4227 << ": Canceling drag and drop because the pointers for the drag "
4228 "window are being canceled.";
4229 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4230 mDragState.reset();
4231 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004232 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4233 ftl::Flags<InputTarget::Flags>(), pointerIds,
4234 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004235 } else {
4236 targets.emplace_back(fallbackTarget);
4237 const auto it = mDisplayInfos.find(motionEntry.displayId);
4238 if (it != mDisplayInfos.end()) {
4239 targets.back().displayTransform = it->second.transform;
4240 targets.back().setDefaultPointerTransform(it->second.transform);
4241 }
4242 }
4243 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004244 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004246 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004247 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004248 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4249 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004250 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004251 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004252 break;
4253 }
Chris Yef59a2f42020-10-16 12:55:26 -07004254 case EventEntry::Type::DEVICE_RESET:
4255 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004256 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004257 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004258 break;
4259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004262 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004263 if (mTracer) {
4264 mTracer->dispatchToTargetHint(*options.traceTracker, targets[0]);
4265 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004266 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004268
hongzuo liu95785e22022-09-06 02:51:35 +00004269 // If the outbound queue was previously empty, start the dispatch cycle going.
4270 if (wasEmpty && !connection->outboundQueue.empty()) {
4271 startDispatchCycleLocked(currentTime, connection);
4272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273}
4274
Svet Ganov5d3bc372020-01-26 23:11:07 -08004275void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004276 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004277 ftl::Flags<InputTarget::Flags> targetFlags,
4278 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004279 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004280 return;
4281 }
4282
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004283 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004284 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004285
4286 if (downEvents.empty()) {
4287 return;
4288 }
4289
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004290 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004291 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4292 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004293 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004294
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004295 const auto [_, touchedWindowState, displayId] =
4296 findTouchStateWindowAndDisplayLocked(connection->getToken());
4297 if (touchedWindowState == nullptr) {
4298 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4299 }
4300 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004301
hongzuo liu95785e22022-09-06 02:51:35 +00004302 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004304 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004305 switch (downEventEntry->type) {
4306 case EventEntry::Type::MOTION: {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004307 if (mTracer) {
4308 static_cast<MotionEntry&>(*downEventEntry).traceTracker =
4309 mTracer->traceDerivedEvent(*downEventEntry, *traceTracker);
4310 }
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004311 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4312 if (windowHandle != nullptr) {
4313 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004314 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004315 pointerIndex++) {
4316 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4317 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004318 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4319 targetFlags, pointerIds, motionEntry.downTime,
4320 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004321 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004322 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004323 const auto it = mDisplayInfos.find(motionEntry.displayId);
4324 if (it != mDisplayInfos.end()) {
4325 targets.back().displayTransform = it->second.transform;
4326 targets.back().setDefaultPointerTransform(it->second.transform);
4327 }
4328 }
4329 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004330 break;
4331 }
4332
4333 case EventEntry::Type::KEY:
4334 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004335 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004336 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004337 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004338 case EventEntry::Type::SENSOR:
4339 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004340 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004341 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004342 break;
4343 }
4344 }
4345
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004346 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhand6b2b052024-02-21 23:25:15 +00004347 if (mTracer) {
4348 mTracer->dispatchToTargetHint(*traceTracker, targets[0]);
4349 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004350 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004351 }
4352
hongzuo liu95785e22022-09-06 02:51:35 +00004353 // If the outbound queue was previously empty, start the dispatch cycle going.
4354 if (wasEmpty && !connection->outboundQueue.empty()) {
4355 startDispatchCycleLocked(downTime, connection);
4356 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004357}
4358
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004360 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4361 nsecs_t splitDownTime) {
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004362 const auto& [action, pointerProperties, pointerCoords] =
4363 MotionEvent::split(originalMotionEntry.action, originalMotionEntry.flags,
4364 /*historySize=*/0, originalMotionEntry.pointerProperties,
4365 originalMotionEntry.pointerCoords, pointerIds);
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004366 if (pointerIds.count() != pointerCoords.size()) {
4367 // TODO(b/329107108): Determine why some IDs in pointerIds were not in originalMotionEntry.
4368 // This is bad. We are missing some of the pointers that we expected to deliver.
4369 // Most likely this indicates that we received an ACTION_MOVE events that has
4370 // different pointer ids than we expected based on the previous ACTION_DOWN
4371 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4372 // in this way.
Siarhei Vishniakoued89cbb2023-10-13 10:42:44 -07004373 ALOGW("Dropping split motion event because the pointer count is %zu but "
Prabir Pradhan1a41fe02024-03-11 18:38:40 +00004374 "we expected there to be %zu pointers. This probably means we received "
4375 "a broken sequence of pointer ids from the input device: %s",
4376 pointerCoords.size(), pointerIds.count(),
4377 originalMotionEntry.getDescription().c_str());
4378 return nullptr;
4379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004381 // TODO(b/327503168): Move this check inside MotionEvent::split once all callers handle it
4382 // correctly.
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004383 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4384 logDispatchStateLocked();
4385 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4386 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4387 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004388 }
4389
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004390 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004391 ATRACE_NAME_IF(ATRACE_ENABLED(),
4392 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4393 ").",
4394 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004395 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004396 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4397 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004398 originalMotionEntry.deviceId, originalMotionEntry.source,
4399 originalMotionEntry.displayId,
4400 originalMotionEntry.policyFlags, action,
4401 originalMotionEntry.actionButton,
4402 originalMotionEntry.flags, originalMotionEntry.metaState,
4403 originalMotionEntry.buttonState,
4404 originalMotionEntry.classification,
4405 originalMotionEntry.edgeFlags,
4406 originalMotionEntry.xPrecision,
4407 originalMotionEntry.yPrecision,
4408 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004409 originalMotionEntry.yCursorPosition, splitDownTime,
Prabir Pradhanbf9b0a82024-02-29 02:23:50 +00004410 pointerProperties, pointerCoords);
Prabir Pradhana67623c2024-02-21 06:57:36 +00004411 if (mTracer) {
4412 splitMotionEntry->traceTracker =
4413 mTracer->traceDerivedEvent(*splitMotionEntry, *originalMotionEntry.traceTracker);
4414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 return splitMotionEntry;
4417}
4418
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004419void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4420 std::scoped_lock _l(mLock);
Liana Kazanova5b8217b2024-07-18 17:44:51 +00004421 // Reset key repeating in case a keyboard device was added or removed or something.
4422 resetKeyRepeatLocked();
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004423 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4424}
4425
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004426void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004427 ALOGD_IF(debugInboundEventDetails(),
4428 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
Linnan Li13bf76a2024-05-05 19:18:02 +08004429 ", deviceId=%d, source=%s, displayId=%s, policyFlags=0x%x, action=%s, flags=0x%x, "
4430 "keyCode=%s, scanCode=0x%x, metaState=0x%x, "
Prabir Pradhan96282b02023-02-24 22:36:17 +00004431 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004432 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004433 args.displayId.toString().c_str(), args.policyFlags,
4434 KeyEvent::actionToString(args.action), args.flags, KeyEvent::getLabel(args.keyCode),
4435 args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004436 Result<void> keyCheck = validateKeyEvent(args.action);
4437 if (!keyCheck.ok()) {
4438 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 return;
4440 }
4441
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004442 uint32_t policyFlags = args.policyFlags;
4443 int32_t flags = args.flags;
4444 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004445 // InputDispatcher tracks and generates key repeats on behalf of
4446 // whatever notifies it, so repeatCount should always be set to 0
4447 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4449 policyFlags |= POLICY_FLAG_VIRTUAL;
4450 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 if (policyFlags & POLICY_FLAG_FUNCTION) {
4453 metaState |= AMETA_FUNCTION_ON;
4454 }
4455
4456 policyFlags |= POLICY_FLAG_TRUSTED;
4457
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004458 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004460 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4461 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4462 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463
Michael Wright2b3c3302018-03-02 17:19:13 +00004464 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004465 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004466 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4467 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470
Antonio Kantekf16f2832021-09-28 04:39:20 +00004471 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 { // acquire lock
4473 mLock.lock();
4474
4475 if (shouldSendKeyToInputFilterLocked(args)) {
4476 mLock.unlock();
4477
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004478 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004479 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 return; // event was consumed by the filter
4481 }
4482
4483 mLock.lock();
4484 }
4485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004487 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4488 args.deviceId, args.source, args.displayId, policyFlags,
4489 args.action, flags, keyCode, args.scanCode, metaState,
4490 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004491 if (mTracer) {
4492 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004495 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 mLock.unlock();
4497 } // release lock
4498
4499 if (needWake) {
4500 mLooper->wake();
4501 }
4502}
4503
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004504bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 return mInputFilterEnabled;
4506}
4507
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004508void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004509 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004510 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08004511 "displayId=%s, policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004512 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004513 "xCursorPosition=%f, yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08004515 args.displayId.toString().c_str(), args.policyFlags,
4516 MotionEvent::actionToString(args.action).c_str(), args.actionButton, args.flags,
Siarhei Vishniakou4125ea42024-07-01 16:38:17 -07004517 args.metaState, args.buttonState, args.xCursorPosition, args.yCursorPosition,
4518 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004519 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004520 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4521 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004522 i, args.pointerProperties[i].id,
4523 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4524 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4525 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4526 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4527 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4528 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4529 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4530 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4531 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4532 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004535
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004536 Result<void> motionCheck =
4537 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4538 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004539 if (!motionCheck.ok()) {
4540 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4541 return;
4542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004544 if (DEBUG_VERIFY_EVENTS) {
4545 auto [it, _] =
4546 mVerifiersByDisplay.try_emplace(args.displayId,
Linnan Li13bf76a2024-05-05 19:18:02 +08004547 StringPrintf("display %s",
4548 args.displayId.toString().c_str()));
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004549 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004550 it->second.processMovement(args.deviceId, args.source, args.action,
4551 args.getPointerCount(), args.pointerProperties.data(),
4552 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004553 if (!result.ok()) {
4554 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4555 }
4556 }
4557
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004558 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004560
4561 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004562 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4563 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004564 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4565 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004566 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568
Antonio Kantekf16f2832021-09-28 04:39:20 +00004569 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 { // acquire lock
4571 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004572 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4573 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4574 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004575 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004576 if (touchStateIt != mTouchStatesByDisplay.end()) {
4577 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004578 if (touchState.hasTouchingPointers(args.deviceId) ||
4579 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004580 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4581 }
4582 }
4583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
4585 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004586 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004587 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004588 displayTransform = it->second.transform;
4589 }
4590
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 mLock.unlock();
4592
4593 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004594 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4595 args.action, args.actionButton, args.flags, args.edgeFlags,
4596 args.metaState, args.buttonState, args.classification,
4597 displayTransform, args.xPrecision, args.yPrecision,
4598 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004599 args.downTime, args.eventTime, args.getPointerCount(),
4600 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601
4602 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004603 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 return; // event was consumed by the filter
4605 }
4606
4607 mLock.lock();
4608 }
4609
4610 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004611 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004612 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4613 args.deviceId, args.source, args.displayId,
4614 policyFlags, args.action, args.actionButton,
4615 args.flags, args.metaState, args.buttonState,
4616 args.classification, args.edgeFlags, args.xPrecision,
4617 args.yPrecision, args.xCursorPosition,
4618 args.yCursorPosition, args.downTime,
4619 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004620 if (mTracer) {
4621 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004624 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4625 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004626 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004627 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004628 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4629 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4630 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004631 }
4632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004633 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 mLock.unlock();
4635 } // release lock
4636
4637 if (needWake) {
4638 mLooper->wake();
4639 }
4640}
4641
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004642void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004643 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004644 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4645 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646 args.id, args.eventTime, args.deviceId, args.source,
4647 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004648 }
Chris Yef59a2f42020-10-16 12:55:26 -07004649
Antonio Kantekf16f2832021-09-28 04:39:20 +00004650 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004651 { // acquire lock
4652 mLock.lock();
4653
4654 // Just enqueue a new sensor event.
4655 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4657 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4658 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004659
4660 needWake = enqueueInboundEventLocked(std::move(newEntry));
4661 mLock.unlock();
4662 } // release lock
4663
4664 if (needWake) {
4665 mLooper->wake();
4666 }
4667}
4668
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004669void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004670 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004671 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4672 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004673 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004674 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004675}
4676
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004677bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004678 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679}
4680
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004681void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004682 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004683 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4684 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004685 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004688 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004690 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004693void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004694 // TODO(b/308677868) Remove device reset from the InputListener interface
Prabir Pradhan65613802023-02-22 23:36:58 +00004695 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004696 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4697 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699
Antonio Kantekf16f2832021-09-28 04:39:20 +00004700 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004702 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004704 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004705 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004706 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004707
4708 for (auto& [_, verifier] : mVerifiersByDisplay) {
4709 verifier.resetDevice(args.deviceId);
4710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 } // release lock
4712
4713 if (needWake) {
4714 mLooper->wake();
4715 }
4716}
4717
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004718void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004719 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004720 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
Hiroki Sato25040232024-02-22 17:21:22 +09004721 args.request.isEnable() ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004722 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004723
Antonio Kantekf16f2832021-09-28 04:39:20 +00004724 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004725 { // acquire lock
4726 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004727 auto entry =
4728 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004729 needWake = enqueueInboundEventLocked(std::move(entry));
4730 } // release lock
4731
4732 if (needWake) {
4733 mLooper->wake();
4734 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004735}
4736
Prabir Pradhan5735a322022-04-11 17:23:34 +00004737InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004738 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004739 InputEventInjectionSync syncMode,
4740 std::chrono::milliseconds timeout,
4741 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004742 Result<void> eventValidation = validateInputEvent(*event);
4743 if (!eventValidation.ok()) {
4744 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4745 return InputEventInjectionResult::FAILED;
4746 }
4747
Prabir Pradhan65613802023-02-22 23:36:58 +00004748 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004749 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4750 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4751 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4752 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004753 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004754 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755
Prabir Pradhan5735a322022-04-11 17:23:34 +00004756 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004758 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004759 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4760 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4761 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4762 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4763 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004764 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004765 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004766 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004767 }
4768
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004769 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4770 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4771
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004772 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004774 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004775 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004776 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004777 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004778 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4779 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4780 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004781 int32_t keyCode = incomingKey.getKeyCode();
4782 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004783 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004784 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004785 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4786 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4787 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004789 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4790 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004791 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792
4793 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4794 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004795 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4797 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4798 std::to_string(t.duration().count()).c_str());
4799 }
4800 }
4801
4802 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004804 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4805 incomingKey.getEventTime(), resolvedDeviceId,
4806 incomingKey.getSource(), incomingKey.getDisplayId(),
4807 policyFlags, action, flags, keyCode,
4808 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004809 incomingKey.getRepeatCount(),
4810 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004811 if (mTracer) {
4812 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4813 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004814 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004815 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 }
4817
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004818 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004819 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004820 const bool isPointerEvent =
4821 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4822 // If a pointer event has no displayId specified, inject it to the default display.
Linnan Li13bf76a2024-05-05 19:18:02 +08004823 const ui::LogicalDisplayId displayId =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004824 isPointerEvent && (event->getDisplayId() == ui::LogicalDisplayId::INVALID)
4825 ? ui::LogicalDisplayId::DEFAULT
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004826 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004827 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828
4829 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004830 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004832 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4833 motionEvent.getAction(), eventTime,
4834 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004835 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4836 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4837 std::to_string(t.duration().count()).c_str());
4838 }
4839 }
4840
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004841 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4842 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4843 }
4844
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004845 mLock.lock();
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004846
Siarhei Vishniakoueb75bc82024-06-04 13:05:45 -07004847 {
4848 // Verify all injected streams, whether the injection is coming from apps or from
4849 // input filter. Print an error if the stream becomes inconsistent with this event.
4850 // An inconsistent injected event sent could cause a crash in the later stages of
4851 // dispatching pipeline.
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004852 auto [it, _] =
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07004853 mInputFilterVerifiersByDisplay.try_emplace(displayId,
4854 std::string("Injection on ") +
4855 displayId.toString());
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00004856 InputVerifier& verifier = it->second;
4857
4858 Result<void> result =
4859 verifier.processMovement(resolvedDeviceId, motionEvent.getSource(),
4860 motionEvent.getAction(),
4861 motionEvent.getPointerCount(),
4862 motionEvent.getPointerProperties(),
4863 motionEvent.getSamplePointerCoords(), flags);
4864 if (!result.ok()) {
4865 logDispatchStateLocked();
4866 LOG(ERROR) << "Inconsistent event: " << motionEvent
4867 << ", reason: " << result.error();
4868 }
4869 }
4870
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004871 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004872 const size_t pointerCount = motionEvent.getPointerCount();
4873 const std::vector<PointerProperties>
4874 pointerProperties(motionEvent.getPointerProperties(),
4875 motionEvent.getPointerProperties() + pointerCount);
4876
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004877 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004878 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004879 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4880 *sampleEventTimes, resolvedDeviceId,
4881 motionEvent.getSource(), displayId, policyFlags,
4882 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004883 motionEvent.getActionButton(), flags,
4884 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004885 motionEvent.getButtonState(),
4886 motionEvent.getClassification(),
4887 motionEvent.getEdgeFlags(),
4888 motionEvent.getXPrecision(),
4889 motionEvent.getYPrecision(),
4890 motionEvent.getRawXCursorPosition(),
4891 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004892 motionEvent.getDownTime(), pointerProperties,
4893 std::vector<PointerCoords>(samplePointerCoords,
4894 samplePointerCoords +
4895 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004896 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004897 if (mTracer) {
4898 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4899 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004900 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004901 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004903 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004904 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004905 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4906 resolvedDeviceId, motionEvent.getSource(), displayId,
4907 policyFlags, motionEvent.getAction(),
4908 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004909 motionEvent.getMetaState(), motionEvent.getButtonState(),
4910 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4911 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4912 motionEvent.getRawXCursorPosition(),
4913 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4914 pointerProperties,
4915 std::vector<PointerCoords>(samplePointerCoords,
4916 samplePointerCoords +
4917 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004918 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4919 motionEvent.getTransform());
Prabir Pradhan2b2d1bf2024-03-05 16:27:56 +00004920 if (mTracer) {
4921 nextInjectedEntry->traceTracker =
4922 mTracer->traceInboundEvent(*nextInjectedEntry);
4923 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004924 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004925 }
4926 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004929 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004930 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004931 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 }
4933
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004935 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004936 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004937 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004938 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004939 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004940 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 }
4942
4943 mLock.unlock();
4944
4945 if (needWake) {
4946 mLooper->wake();
4947 }
4948
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004949 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004951 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004953 if (syncMode == InputEventInjectionSync::NONE) {
4954 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 } else {
4956 for (;;) {
4957 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004958 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 break;
4960 }
4961
4962 nsecs_t remainingTimeout = endTime - now();
4963 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004964 if (DEBUG_INJECTION) {
4965 ALOGD("injectInputEvent - Timed out waiting for injection result "
4966 "to become available.");
4967 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004968 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 break;
4970 }
4971
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004972 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 }
4974
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004975 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4976 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004978 if (DEBUG_INJECTION) {
4979 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4980 injectionState->pendingForegroundDispatches);
4981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 nsecs_t remainingTimeout = endTime - now();
4983 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004984 if (DEBUG_INJECTION) {
4985 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4986 "dispatches to finish.");
4987 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004988 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 break;
4990 }
4991
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004992 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 }
4994 }
4995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 } // release lock
4997
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004998 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004999 LOG(INFO) << "injectInputEvent - Finished with result "
5000 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
5003 return injectionResult;
5004}
5005
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005006std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05005007 std::array<uint8_t, 32> calculatedHmac;
5008 std::unique_ptr<VerifiedInputEvent> result;
5009 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005010 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05005011 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
5012 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
5013 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005014 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05005015 break;
5016 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005017 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05005018 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
5019 VerifiedMotionEvent verifiedMotionEvent =
5020 verifiedMotionEventFromMotionEvent(motionEvent);
5021 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07005022 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05005023 break;
5024 }
5025 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08005026 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05005027 return nullptr;
5028 }
5029 }
5030 if (calculatedHmac == INVALID_HMAC) {
5031 return nullptr;
5032 }
tyiu1573a672023-02-21 22:38:32 +00005033 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05005034 return nullptr;
5035 }
5036 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08005037}
5038
Prabir Pradhan24047542023-11-02 17:14:59 +00005039void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005040 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005041 if (!entry.injectionState) {
5042 // Not an injected event.
5043 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005045
5046 InjectionState& injectionState = *entry.injectionState;
5047 if (DEBUG_INJECTION) {
5048 LOG(INFO) << "Setting input event injection result to "
5049 << ftl::enum_string(injectionResult);
5050 }
5051
5052 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
5053 // Log the outcome since the injector did not wait for the injection result.
5054 switch (injectionResult) {
5055 case InputEventInjectionResult::SUCCEEDED:
5056 ALOGV("Asynchronous input event injection succeeded.");
5057 break;
5058 case InputEventInjectionResult::TARGET_MISMATCH:
5059 ALOGV("Asynchronous input event injection target mismatch.");
5060 break;
5061 case InputEventInjectionResult::FAILED:
5062 ALOGW("Asynchronous input event injection failed.");
5063 break;
5064 case InputEventInjectionResult::TIMED_OUT:
5065 ALOGW("Asynchronous input event injection timed out.");
5066 break;
5067 case InputEventInjectionResult::PENDING:
5068 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5069 break;
5070 }
5071 }
5072
5073 injectionState.injectionResult = injectionResult;
5074 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075}
5076
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005077void InputDispatcher::transformMotionEntryForInjectionLocked(
5078 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005079 // Input injection works in the logical display coordinate space, but the input pipeline works
5080 // display space, so we need to transform the injected events accordingly.
5081 const auto it = mDisplayInfos.find(entry.displayId);
5082 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005083 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005084
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005085 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5086 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5087 const vec2 cursor =
5088 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5089 {entry.xCursorPosition, entry.yCursorPosition});
5090 entry.xCursorPosition = cursor.x;
5091 entry.yCursorPosition = cursor.y;
5092 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005093 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005094 entry.pointerCoords[i] =
Prabir Pradhan9a53b552024-06-04 02:59:40 +00005095 MotionEvent::calculateTransformedCoords(entry.source, entry.flags,
5096 transformToDisplay, entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005097 }
5098}
5099
Prabir Pradhan24047542023-11-02 17:14:59 +00005100void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005101 if (entry.injectionState) {
5102 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
5104}
5105
Prabir Pradhan24047542023-11-02 17:14:59 +00005106void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005107 if (entry.injectionState) {
5108 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005110 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005111 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113 }
5114}
5115
chaviw98318de2021-05-19 16:45:23 -05005116const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005117 ui::LogicalDisplayId displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005118 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005119 auto it = mWindowHandlesByDisplay.find(displayId);
5120 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005121}
5122
chaviw98318de2021-05-19 16:45:23 -05005123sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005124 const sp<IBinder>& windowHandleToken, std::optional<ui::LogicalDisplayId> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005125 if (windowHandleToken == nullptr) {
5126 return nullptr;
5127 }
5128
Prabir Pradhan16463382023-10-12 23:03:19 +00005129 if (!displayId) {
5130 // Look through all displays.
Linnan Li13bf76a2024-05-05 19:18:02 +08005131 for (const auto& [_, windowHandles] : mWindowHandlesByDisplay) {
Prabir Pradhan16463382023-10-12 23:03:19 +00005132 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5133 if (windowHandle->getToken() == windowHandleToken) {
5134 return windowHandle;
5135 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005138 return nullptr;
5139 }
5140
Prabir Pradhan16463382023-10-12 23:03:19 +00005141 // Only look through the requested display.
5142 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005143 if (windowHandle->getToken() == windowHandleToken) {
5144 return windowHandle;
5145 }
5146 }
5147 return nullptr;
5148}
5149
chaviw98318de2021-05-19 16:45:23 -05005150sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5151 const sp<WindowInfoHandle>& windowHandle) const {
Linnan Li13bf76a2024-05-05 19:18:02 +08005152 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005153 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005154 if (handle->getId() == windowHandle->getId() &&
5155 handle->getToken() == windowHandle->getToken()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005156 if (windowHandle->getInfo()->displayId != displayId) {
5157 ALOGE("Found window %s in display %s"
5158 ", but it should belong to display %s",
5159 windowHandle->getName().c_str(), displayId.toString().c_str(),
5160 windowHandle->getInfo()->displayId.toString().c_str());
Mady Mellor017bcd12020-06-23 19:12:00 +00005161 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005162 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
5165 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005166 return nullptr;
5167}
5168
Linnan Li13bf76a2024-05-05 19:18:02 +08005169sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(
5170 ui::LogicalDisplayId displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005171 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5172 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173}
5174
Linnan Li13bf76a2024-05-05 19:18:02 +08005175ui::Transform InputDispatcher::getTransformLocked(ui::LogicalDisplayId displayId) const {
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005176 auto displayInfoIt = mDisplayInfos.find(displayId);
5177 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5178 : kIdentityTransform;
5179}
5180
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005181bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5182 const MotionEntry& motionEntry) const {
5183 const WindowInfo& info = *window->getInfo();
5184
5185 // Skip spy window targets that are not valid for targeted injection.
5186 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005187 return false;
5188 }
5189
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005190 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5191 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5192 return false;
5193 }
5194
5195 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5196 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5197 window->getName().c_str());
5198 return false;
5199 }
5200
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005201 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005202 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005203 ALOGW("Not sending touch to %s because there's no corresponding connection",
5204 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005205 return false;
5206 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005207
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005208 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005209 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005210 return false;
5211 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005212
5213 // Drop events that can't be trusted due to occlusion
5214 const auto [x, y] = resolveTouchedPosition(motionEntry);
5215 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5216 if (!isTouchTrustedLocked(occlusionInfo)) {
5217 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005218 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005219 for (const auto& log : occlusionInfo.debugInfo) {
5220 ALOGD("%s", log.c_str());
5221 }
5222 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005223 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5224 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005225 return false;
5226 }
5227
5228 // Drop touch events if requested by input feature
5229 if (shouldDropInput(motionEntry, window)) {
5230 return false;
5231 }
5232
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005233 // Ignore touches if stylus is down anywhere on screen
5234 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5235 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5236 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5237 return false;
5238 }
5239
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005240 return true;
5241}
5242
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005243void InputDispatcher::updateWindowHandlesForDisplayLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005244 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5245 ui::LogicalDisplayId displayId) {
chaviw98318de2021-05-19 16:45:23 -05005246 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005247 // Remove all handles on a display if there are no windows left.
5248 mWindowHandlesByDisplay.erase(displayId);
5249 return;
5250 }
5251
5252 // Since we compare the pointer of input window handles across window updates, we need
5253 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005254 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5255 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5256 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005257 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005258 }
5259
chaviw98318de2021-05-19 16:45:23 -05005260 std::vector<sp<WindowInfoHandle>> newHandles;
5261 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005262 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005263 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005264 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005265 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005266 const bool canReceiveInput =
5267 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5268 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005269 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005270 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005271 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005272 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005273 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005274 }
5275
5276 if (info->displayId != displayId) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005277 ALOGE("Window %s updated by wrong display %s, should belong to display %s",
5278 handle->getName().c_str(), displayId.toString().c_str(),
5279 info->displayId.toString().c_str());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005280 continue;
5281 }
5282
Robert Carredd13602020-04-13 17:24:34 -07005283 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
Linnan Li13bf76a2024-05-05 19:18:02 +08005284 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005285 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005286 oldHandle->updateFrom(handle);
5287 newHandles.push_back(oldHandle);
5288 } else {
5289 newHandles.push_back(handle);
5290 }
5291 }
5292
5293 // Insert or replace
5294 mWindowHandlesByDisplay[displayId] = newHandles;
5295}
5296
Arthur Hungb92218b2018-08-14 12:00:21 +08005297/**
5298 * Called from InputManagerService, update window handle list by displayId that can receive input.
5299 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5300 * If set an empty list, remove all handles from the specific display.
5301 * For focused handle, check if need to change and send a cancel event to previous one.
5302 * For removed handle, check if need to send a cancel event if already in touch.
5303 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005304void InputDispatcher::setInputWindowsLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005305 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles,
5306 ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005307 if (DEBUG_FOCUS) {
5308 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005309 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005310 windowList += iwh->getName() + " ";
5311 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005312 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005313 }
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005314 ScopedSyntheticEventTracer traceContext(mTracer);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
Prabir Pradhand65552b2021-10-07 11:23:50 -07005316 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005317 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005318 const WindowInfo& info = *window->getInfo();
5319
5320 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005321 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005322 if (noInputWindow && window->getToken() != nullptr) {
5323 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5324 window->getName().c_str());
5325 window->releaseChannel();
5326 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005327
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005328 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005329 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5330 !info.inputConfig.test(
5331 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005332 "%s has feature SPY, but is not a trusted overlay.",
5333 window->getName().c_str());
5334
Prabir Pradhand65552b2021-10-07 11:23:50 -07005335 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005336 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5337 !info.inputConfig.test(
5338 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005339 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5340 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005341 }
5342
Arthur Hung72d8dc32020-03-28 00:48:39 +00005343 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005344 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005345 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346
chaviw98318de2021-05-19 16:45:23 -05005347 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005348
chaviw98318de2021-05-19 16:45:23 -05005349 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005350
Vishnu Nairc519ff72021-01-21 08:23:08 -08005351 std::optional<FocusResolver::FocusChanges> changes =
5352 mFocusResolver.setInputWindows(displayId, windowHandles);
5353 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005354 onFocusChangedLocked(*changes, traceContext.getTracker(), removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356
Linnan Li72352222024-04-12 18:55:57 +08005357 if (const auto& it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
5358 TouchState& state = it->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005359 for (size_t i = 0; i < state.windows.size();) {
5360 TouchedWindow& touchedWindow = state.windows[i];
Linnan Li72352222024-04-12 18:55:57 +08005361 if (getWindowHandleLocked(touchedWindow.windowHandle) != nullptr) {
5362 i++;
5363 continue;
5364 }
5365 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5366 << " in display %" << displayId;
5367 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5368 "touched window was removed", traceContext.getTracker());
5369 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5370 // Since we are about to drop the touch, cancel the events for the wallpaper as
5371 // well.
5372 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5373 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5374 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5375 for (const DeviceId deviceId : touchedWindow.getTouchingDeviceIds()) {
5376 if (const auto& ww = state.getWallpaperWindow(deviceId); ww != nullptr) {
5377 options.deviceId = deviceId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005378 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 }
Linnan Li72352222024-04-12 18:55:57 +08005382 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383 }
arthurhungb89ccb02020-12-30 16:19:01 +08005384
arthurhung6d4bed92021-03-17 11:59:33 +08005385 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005386 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005387 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005388 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005389 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005390 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5391 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005392 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005393 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005394 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005395
Arthur Hung72d8dc32020-03-28 00:48:39 +00005396 // Release information for windows that are no longer present.
5397 // This ensures that unused input channels are released promptly.
5398 // Otherwise, they might stick around until the window handle is destroyed
5399 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005400 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005401 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005402 if (DEBUG_FOCUS) {
5403 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005404 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005405 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005406 }
chaviw291d88a2019-02-14 10:33:58 -08005407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408}
5409
5410void InputDispatcher::setFocusedApplication(
Linnan Li13bf76a2024-05-05 19:18:02 +08005411 ui::LogicalDisplayId displayId,
5412 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005413 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005414 ALOGD("setFocusedApplication displayId=%s %s", displayId.toString().c_str(),
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005415 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5416 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005417 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005418 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005419 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 } // release lock
5421
5422 // Wake up poll loop since it may need to make new input dispatching choices.
5423 mLooper->wake();
5424}
5425
Vishnu Nair599f1412021-06-21 10:39:58 -07005426void InputDispatcher::setFocusedApplicationLocked(
Linnan Li13bf76a2024-05-05 19:18:02 +08005427 ui::LogicalDisplayId displayId,
5428 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Vishnu Nair599f1412021-06-21 10:39:58 -07005429 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5430 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5431
5432 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5433 return; // This application is already focused. No need to wake up or change anything.
5434 }
5435
5436 // Set the new application handle.
5437 if (inputApplicationHandle != nullptr) {
5438 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5439 } else {
5440 mFocusedApplicationHandlesByDisplay.erase(displayId);
5441 }
5442
5443 // No matter what the old focused application was, stop waiting on it because it is
5444 // no longer focused.
5445 resetNoFocusedWindowTimeoutLocked();
5446}
5447
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005448void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5449 if (interval.count() < 0) {
5450 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5451 }
5452 std::scoped_lock _l(mLock);
5453 mMinTimeBetweenUserActivityPokes = interval;
5454}
5455
Tiger Huang721e26f2018-07-24 22:26:19 +08005456/**
5457 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5458 * the display not specified.
5459 *
5460 * We track any unreleased events for each window. If a window loses the ability to receive the
5461 * released event, we will send a cancel event to it. So when the focused display is changed, we
5462 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5463 * display. The display-specified events won't be affected.
5464 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005465void InputDispatcher::setFocusedDisplay(ui::LogicalDisplayId displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005466 if (DEBUG_FOCUS) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005467 ALOGD("setFocusedDisplay displayId=%s", displayId.toString().c_str());
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005468 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005469 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005470 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005471 ScopedSyntheticEventTracer traceContext(mTracer);
Tiger Huang721e26f2018-07-24 22:26:19 +08005472
5473 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005474 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005475 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005476 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005477 const auto windowHandle =
5478 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5479 if (windowHandle == nullptr) {
5480 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005481 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005482 CancelationOptions
5483 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005484 "The display which contains this window no longer has focus.",
5485 traceContext.getTracker());
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005486 options.displayId = ui::LogicalDisplayId::INVALID;
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005487 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005488 }
5489 mFocusedDisplayId = displayId;
Arpit Singhb65e2bd2024-06-03 09:48:16 +00005490 // Enqueue a command to run outside the lock to tell the policy that the focused display
5491 // changed.
5492 auto command = [this]() REQUIRES(mLock) {
5493 scoped_unlock unlock(mLock);
5494 mPolicy.notifyFocusedDisplayChanged(mFocusedDisplayId);
5495 };
5496 postCommandLocked(std::move(command));
Tiger Huang721e26f2018-07-24 22:26:19 +08005497
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00005498 // Only a window on the focused display can have Pointer Capture, so disable the active
5499 // Pointer Capture session if there is one, since the focused display changed.
5500 disablePointerCaptureForcedLocked();
5501
Chris Ye3c2d6f52020-08-09 10:39:48 -07005502 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005503 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005504 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005505
Vishnu Nairad321cd2020-08-20 16:40:21 -07005506 if (newFocusedWindowToken == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005507 ALOGW("Focused display #%s does not have a focused window.",
5508 displayId.toString().c_str());
Vishnu Nairc519ff72021-01-21 08:23:08 -08005509 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005510 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005511 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005512 }
5513 }
5514 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005515 } // release lock
5516
5517 // Wake up poll loop since it may need to make new input dispatching choices.
5518 mLooper->wake();
5519}
5520
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005522 if (DEBUG_FOCUS) {
5523 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
5526 bool changed;
5527 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005528 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529
5530 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5531 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 }
5534
5535 if (mDispatchEnabled && !enabled) {
5536 resetAndDropEverythingLocked("dispatcher is being disabled");
5537 }
5538
5539 mDispatchEnabled = enabled;
5540 mDispatchFrozen = frozen;
5541 changed = true;
5542 } else {
5543 changed = false;
5544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 } // release lock
5546
5547 if (changed) {
5548 // Wake up poll loop since it may need to make new input dispatching choices.
5549 mLooper->wake();
5550 }
5551}
5552
5553void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005554 if (DEBUG_FOCUS) {
5555 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557
5558 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005559 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560
5561 if (mInputFilterEnabled == enabled) {
5562 return;
5563 }
5564
5565 mInputFilterEnabled = enabled;
5566 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5567 } // release lock
5568
5569 // Wake up poll loop since there might be work to do to drop everything.
5570 mLooper->wake();
5571}
5572
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005573bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Linnan Li13bf76a2024-05-05 19:18:02 +08005574 bool hasPermission, ui::LogicalDisplayId displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005575 bool needWake = false;
5576 {
5577 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005578 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005579 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08005580 "hasPermission=%s, target displayId=%s, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005581 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08005582 toString(hasPermission), displayId.toString().c_str(),
Antonio Kantek15beb512022-06-13 22:35:41 +00005583 mTouchModePerDisplay.count(displayId) == 0
5584 ? "not set"
5585 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5586
Antonio Kantek15beb512022-06-13 22:35:41 +00005587 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5588 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005589 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005590 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005591 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005592 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5593 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005594 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005595 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005596 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005597 return false;
5598 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005599 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005600 mTouchModePerDisplay[displayId] = inTouchMode;
5601 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5602 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005603 needWake = enqueueInboundEventLocked(std::move(entry));
5604 } // release lock
5605
5606 if (needWake) {
5607 mLooper->wake();
5608 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005609 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005610}
5611
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005612bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005613 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5614 if (focusedToken == nullptr) {
5615 return false;
5616 }
5617 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5618 return isWindowOwnedBy(windowHandle, pid, uid);
5619}
5620
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005621bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005622 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5623 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5624 const sp<WindowInfoHandle> windowHandle =
5625 getWindowHandleLocked(connectionToken);
5626 return isWindowOwnedBy(windowHandle, pid, uid);
5627 }) != mInteractionConnectionTokens.end();
5628}
5629
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005630void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5631 if (opacity < 0 || opacity > 1) {
5632 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5633 return;
5634 }
5635
5636 std::scoped_lock lock(mLock);
5637 mMaximumObscuringOpacityForTouch = opacity;
5638}
5639
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005640std::tuple<TouchState*, TouchedWindow*, ui::LogicalDisplayId>
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005641InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005642 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5643 for (TouchedWindow& w : state.windows) {
5644 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005645 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005646 }
5647 }
5648 }
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07005649 return std::make_tuple(nullptr, nullptr, ui::LogicalDisplayId::DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005650}
5651
Siarhei Vishniakou07cdda92024-07-01 16:45:08 -07005652std::tuple<const TouchState*, const TouchedWindow*, ui::LogicalDisplayId>
5653InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) const {
5654 return const_cast<InputDispatcher*>(this)->findTouchStateWindowAndDisplayLocked(token);
5655}
5656
5657bool InputDispatcher::windowHasTouchingPointersLocked(const sp<WindowInfoHandle>& windowHandle,
5658 DeviceId deviceId) const {
5659 const auto& [touchState, touchedWindow, _] =
5660 findTouchStateWindowAndDisplayLocked(windowHandle->getToken());
5661 if (touchState == nullptr) {
5662 // No touching pointers at all
5663 return false;
5664 }
5665 return touchState->hasTouchingPointers(deviceId);
5666}
5667
Prabir Pradhan367f3432024-02-13 23:05:58 +00005668bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5669 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005670 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005671 if (DEBUG_FOCUS) {
5672 ALOGD("Trivial transfer to same window.");
5673 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005674 return true;
5675 }
5676
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005678 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679
Arthur Hungabbb9d82021-09-01 14:52:30 +00005680 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005681 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005682
Arthur Hungabbb9d82021-09-01 14:52:30 +00005683 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005684 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 return false;
5686 }
Linnan Li72352222024-04-12 18:55:57 +08005687 std::set<DeviceId> deviceIds = touchedWindow->getTouchingDeviceIds();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005688 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005689 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5690 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005691 return false;
5692 }
Linnan Li72352222024-04-12 18:55:57 +08005693 const DeviceId deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005694
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005695 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5696 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5697 if (!toWindowHandle) {
5698 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005699 return false;
5700 }
5701
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005702 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005703 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005704 touchedWindow->windowHandle->getName().c_str(),
5705 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
5707
Arthur Hungabbb9d82021-09-01 14:52:30 +00005708 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005709 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005710 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005711 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712
Arthur Hungabbb9d82021-09-01 14:52:30 +00005713 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005714 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005715 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005716 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005717 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005718 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005719 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005720 // Transferring touch focus using this API should not effect the focused window.
5721 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005722 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005723 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724
Arthur Hungabbb9d82021-09-01 14:52:30 +00005725 // Store the dragging window.
5726 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005727 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005728 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5729 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005730 return false;
5731 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005732 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005733 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005734 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 }
5736
Arthur Hungabbb9d82021-09-01 14:52:30 +00005737 // Synthesize cancel for old window and down for new window.
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005738 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005739 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5740 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005741 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005742 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005743 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005744 "transferring touch from this window to another window",
5745 traceContext.getTracker());
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005746 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005747
5748 // Check if the wallpaper window should deliver the corresponding event.
5749 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005750 *state, deviceId, pointers, traceContext.getTracker());
Linnan Li72352222024-04-12 18:55:57 +08005751
5752 // Because new window may have a wallpaper window, it will merge input state from it
5753 // parent window, after this the firstNewPointerIdx in input state will be reset, then
5754 // it will cause new move event be thought inconsistent, so we should synthesize the
5755 // down event after it reset.
5756 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5757 newTargetFlags,
5758 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 } // release lock
5761
5762 // Wake up poll loop since it may need to make new input dispatching choices.
5763 mLooper->wake();
5764 return true;
5765}
5766
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005767/**
5768 * Get the touched foreground window on the given display.
5769 * Return null if there are no windows touched on that display, or if more than one foreground
5770 * window is being touched.
5771 */
Linnan Li13bf76a2024-05-05 19:18:02 +08005772sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(
5773 ui::LogicalDisplayId displayId) const {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005774 auto stateIt = mTouchStatesByDisplay.find(displayId);
5775 if (stateIt == mTouchStatesByDisplay.end()) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005776 ALOGI("No touch state on display %s", displayId.toString().c_str());
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005777 return nullptr;
5778 }
5779
5780 const TouchState& state = stateIt->second;
5781 sp<WindowInfoHandle> touchedForegroundWindow;
5782 // If multiple foreground windows are touched, return nullptr
5783 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005784 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005785 if (touchedForegroundWindow != nullptr) {
5786 ALOGI("Two or more foreground windows: %s and %s",
5787 touchedForegroundWindow->getName().c_str(),
5788 window.windowHandle->getName().c_str());
5789 return nullptr;
5790 }
5791 touchedForegroundWindow = window.windowHandle;
5792 }
5793 }
5794 return touchedForegroundWindow;
5795}
5796
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005797// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005798bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
Linnan Li13bf76a2024-05-05 19:18:02 +08005799 ui::LogicalDisplayId displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005800 sp<IBinder> fromToken;
5801 { // acquire lock
5802 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005803 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005804 if (toWindowHandle == nullptr) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005805 ALOGW("Could not find window associated with token=%p on display %s",
5806 destChannelToken.get(), displayId.toString().c_str());
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005807 return false;
5808 }
5809
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005810 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5811 if (from == nullptr) {
5812 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5813 return false;
5814 }
5815
5816 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005817 } // release lock
5818
Prabir Pradhan367f3432024-02-13 23:05:58 +00005819 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005820}
5821
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005823 if (DEBUG_FOCUS) {
5824 ALOGD("Resetting and dropping all events (%s).", reason);
5825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826
Prabir Pradhand6b2b052024-02-21 23:25:15 +00005827 ScopedSyntheticEventTracer traceContext(mTracer);
5828 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason,
5829 traceContext.getTracker());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 synthesizeCancelationEventsForAllConnectionsLocked(options);
5831
5832 resetKeyRepeatLocked();
5833 releasePendingEventLocked();
5834 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005835 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005837 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005838 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839}
5840
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005841void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005842 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 dumpDispatchStateLocked(dump);
5844
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005845 std::istringstream stream(dump);
5846 std::string line;
5847
5848 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005849 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850 }
5851}
5852
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005853std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005854 std::string dump;
5855
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005856 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
Hiroki Sato25040232024-02-22 17:21:22 +09005857 toString(mCurrentPointerCaptureRequest.isEnable()));
Prabir Pradhan99987712020-11-10 18:43:05 -08005858
5859 std::string windowName = "None";
5860 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005861 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005862 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5863 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5864 : "token has capture without window";
5865 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005866 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005867
5868 return dump;
5869}
5870
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005871void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005872 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5873 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5874 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Linnan Li13bf76a2024-05-05 19:18:02 +08005875 dump += StringPrintf(INDENT "FocusedDisplayId: %s\n", mFocusedDisplayId.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876
Tiger Huang721e26f2018-07-24 22:26:19 +08005877 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5878 dump += StringPrintf(INDENT "FocusedApplications:\n");
5879 for (auto& it : mFocusedApplicationHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005880 const ui::LogicalDisplayId displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005881 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005882 const std::chrono::duration timeout =
5883 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Linnan Li13bf76a2024-05-05 19:18:02 +08005884 dump += StringPrintf(INDENT2 "displayId=%s, name='%s', dispatchingTimeout=%" PRId64
5885 "ms\n",
5886 displayId.toString().c_str(), applicationHandle->getName().c_str(),
5887 millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005890 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005892
Vishnu Nairc519ff72021-01-21 08:23:08 -08005893 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005894 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005896 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005897 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005898 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005899 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
Linnan Li13bf76a2024-05-05 19:18:02 +08005900 dump += INDENT2 + displayId.toString() + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 }
5902 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005903 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 }
5905
arthurhung6d4bed92021-03-17 11:59:33 +08005906 if (mDragState) {
5907 dump += StringPrintf(INDENT "DragState:\n");
5908 mDragState->dump(dump, INDENT2);
5909 }
5910
Arthur Hungb92218b2018-08-14 12:00:21 +08005911 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005912 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005913 dump += StringPrintf(INDENT "Display: %s\n", displayId.toString().c_str());
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005914 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5915 const auto& displayInfo = it->second;
5916 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5917 displayInfo.logicalHeight);
5918 displayInfo.transform.dump(dump, "transform", INDENT4);
5919 } else {
5920 dump += INDENT2 "No DisplayInfo found!\n";
5921 }
5922
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005923 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005924 dump += INDENT2 "Windows:\n";
5925 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005926 dump += StringPrintf(INDENT3 "%zu: %s", i,
5927 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005928 }
5929 } else {
5930 dump += INDENT2 "Windows: <none>\n";
5931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 }
5933 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005934 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935 }
5936
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005937 if (!mGlobalMonitorsByDisplay.empty()) {
5938 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08005939 dump += StringPrintf(INDENT "Global monitors on display %s:\n",
5940 displayId.toString().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005941 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005944 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 }
5946
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005947 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948
5949 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005950 if (!mRecentQueue.empty()) {
5951 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005952 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005953 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005954 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005955 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 }
5957 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005958 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 }
5960
5961 // Dump event currently being dispatched.
5962 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005963 dump += INDENT "PendingEvent:\n";
5964 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005965 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005966 dump += StringPrintf(", age=%" PRId64 "ms\n",
5967 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005969 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 }
5971
5972 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005973 if (!mInboundQueue.empty()) {
5974 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005975 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005976 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005977 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005978 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 }
5980 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005981 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 }
5983
Prabir Pradhancef936d2021-07-21 16:17:52 +00005984 if (!mCommandQueue.empty()) {
5985 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5986 } else {
5987 dump += INDENT "CommandQueue: <empty>\n";
5988 }
5989
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005990 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005991 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005992 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005993 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005994 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005995 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005996 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005997 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005998 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005999
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006000 if (!connection->outboundQueue.empty()) {
6001 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
6002 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006003 dump += dumpQueue(connection->outboundQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004 }
6005
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07006006 if (!connection->waitQueue.empty()) {
6007 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
6008 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05006009 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006011 std::string inputStateDump = streamableToString(connection->inputState);
6012 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006013 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08006014 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07006015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 }
6017 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006018 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019 }
6020
Antonio Kantek15beb512022-06-13 22:35:41 +00006021 if (!mTouchModePerDisplay.empty()) {
6022 dump += INDENT "TouchModePerDisplay:\n";
6023 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
Linnan Li13bf76a2024-05-05 19:18:02 +08006024 dump += StringPrintf(INDENT2 "Display: %s TouchMode: %s\n",
6025 displayId.toString().c_str(), std::to_string(touchMode).c_str());
Antonio Kantek15beb512022-06-13 22:35:41 +00006026 }
6027 } else {
6028 dump += INDENT "TouchModePerDisplay: <none>\n";
6029 }
6030
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006031 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006032 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
6033 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
6034 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00006035 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00006036 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00006037 dump += INDENT "InputTracer: ";
6038 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039}
6040
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07006041void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00006042 const size_t numMonitors = monitors.size();
6043 for (size_t i = 0; i < numMonitors; i++) {
6044 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006045 const std::shared_ptr<Connection>& connection = monitor.connection;
6046 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00006047 dump += "\n";
6048 }
6049}
6050
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006051class LooperEventCallback : public LooperCallback {
6052public:
6053 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
6054 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
6055
6056private:
6057 std::function<int(int events)> mCallback;
6058};
6059
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006060Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006061 if (DEBUG_CHANNEL_CREATION) {
6062 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
6063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006065 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006066 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006067 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006068
6069 if (result) {
6070 return base::Error(result) << "Failed to open input channel pair with name " << name;
6071 }
6072
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006074 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006075 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006076 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006077 std::shared_ptr<Connection> connection =
6078 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
6079 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006081 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
6082 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006083 ALOGE("Created a new connection, but the token %p is already known", token.get());
6084 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006085
6086 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6087 this, std::placeholders::_1, token);
6088
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006089 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006090 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 } // release lock
6092
6093 // Wake the looper because some connections have changed.
6094 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006095 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096}
6097
Linnan Li13bf76a2024-05-05 19:18:02 +08006098Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
6099 ui::LogicalDisplayId displayId, const std::string& name, gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006100 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006101 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006102 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006103 if (result) {
6104 return base::Error(result) << "Failed to open input channel pair with name " << name;
6105 }
6106
Michael Wright3dd60e22019-03-27 22:06:44 +00006107 { // acquire lock
6108 std::scoped_lock _l(mLock);
6109
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07006110 if (displayId < ui::LogicalDisplayId::DEFAULT) {
Garfield Tan15601662020-09-22 15:32:38 -07006111 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6112 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006113 }
6114
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006115 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006116 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006117 std::shared_ptr<Connection> connection =
6118 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6119 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006120
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006121 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6122 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006123 ALOGE("Created a new connection, but the token %p is already known", token.get());
6124 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006125
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006126 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6127 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006128
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006129 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006130
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006131 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006132 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006133 }
Garfield Tan15601662020-09-22 15:32:38 -07006134
Michael Wright3dd60e22019-03-27 22:06:44 +00006135 // Wake the looper because some connections have changed.
6136 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006137 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006138}
6139
Garfield Tan15601662020-09-22 15:32:38 -07006140status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006142 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143
Harry Cutts33476232023-01-30 19:57:29 +00006144 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145 if (status) {
6146 return status;
6147 }
6148 } // release lock
6149
6150 // Wake the poll loop because removing the connection may have changed the current
6151 // synchronization state.
6152 mLooper->wake();
6153 return OK;
6154}
6155
Garfield Tan15601662020-09-22 15:32:38 -07006156status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6157 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006158 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006159 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006160 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 return BAD_VALUE;
6162 }
6163
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006164 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006165
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006167 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168 }
6169
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006170 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171
6172 nsecs_t currentTime = now();
6173 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6174
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006175 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176 return OK;
6177}
6178
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006179void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006180 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6181 auto& [displayId, monitors] = *it;
6182 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006183 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006184 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006185
Michael Wright3dd60e22019-03-27 22:06:44 +00006186 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006187 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006188 } else {
6189 ++it;
6190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191 }
6192}
6193
Michael Wright3dd60e22019-03-27 22:06:44 +00006194status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006195 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006196 return pilferPointersLocked(token);
6197}
Michael Wright3dd60e22019-03-27 22:06:44 +00006198
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006199status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006200 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6201 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006202 LOG(WARNING)
6203 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006204 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006205 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006206
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006207 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006208 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006209 LOG(WARNING)
6210 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6211 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006212 return BAD_VALUE;
6213 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006214 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006215 if (deviceIds.empty()) {
6216 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006217 return BAD_VALUE;
6218 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006219
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006220 ScopedSyntheticEventTracer traceContext(mTracer);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006221 for (const DeviceId deviceId : deviceIds) {
6222 TouchState& state = *statePtr;
6223 TouchedWindow& window = *windowPtr;
6224 // Send cancel events to all the input channels we're stealing from.
6225 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006226 "input channel stole pointer stream", traceContext.getTracker());
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006227 options.deviceId = deviceId;
6228 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006229 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6230 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006231 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006232
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006233 std::string canceledWindows;
6234 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006235 if (w.windowHandle->getToken() != token) {
6236 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006237 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006238 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006239 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006240 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006241 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006242 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006243 << " is stealing input gesture for device " << deviceId << " from "
6244 << canceledWindows;
6245
6246 // Prevent the gesture from being sent to any other windows.
6247 // This only blocks relevant pointers to be sent to other windows
6248 window.addPilferingPointers(deviceId, pointerIds);
6249
6250 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006251 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006252 return OK;
6253}
6254
Prabir Pradhan99987712020-11-10 18:43:05 -08006255void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6256 { // acquire lock
6257 std::scoped_lock _l(mLock);
6258 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006259 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006260 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6261 windowHandle != nullptr ? windowHandle->getName().c_str()
6262 : "token without window");
6263 }
6264
Vishnu Nairc519ff72021-01-21 08:23:08 -08006265 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006266 if (focusedToken != windowToken) {
6267 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6268 enabled ? "enable" : "disable");
6269 return;
6270 }
6271
Hiroki Sato25040232024-02-22 17:21:22 +09006272 if (enabled == mCurrentPointerCaptureRequest.isEnable()) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006273 ALOGW("Ignoring request to %s Pointer Capture: "
6274 "window has %s requested pointer capture.",
6275 enabled ? "enable" : "disable", enabled ? "already" : "not");
6276 return;
6277 }
6278
Christine Franksb768bb42021-11-29 12:11:31 -08006279 if (enabled) {
6280 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6281 mIneligibleDisplaysForPointerCapture.end(),
6282 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6283 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6284 return;
6285 }
6286 }
6287
Hiroki Sato25040232024-02-22 17:21:22 +09006288 setPointerCaptureLocked(enabled ? windowToken : nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08006289 } // release lock
6290
6291 // Wake the thread to process command entries.
6292 mLooper->wake();
6293}
6294
Linnan Li13bf76a2024-05-05 19:18:02 +08006295void InputDispatcher::setDisplayEligibilityForPointerCapture(ui::LogicalDisplayId displayId,
6296 bool isEligible) {
Christine Franksb768bb42021-11-29 12:11:31 -08006297 { // acquire lock
6298 std::scoped_lock _l(mLock);
6299 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6300 if (!isEligible) {
6301 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6302 }
6303 } // release lock
6304}
6305
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006306std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006307 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006308 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006309 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006310 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006311 }
6312 }
6313 }
6314 return std::nullopt;
6315}
6316
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006317std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6318 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006319 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006320 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006321 }
6322
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006323 for (const auto& [token, connection] : mConnectionsByToken) {
6324 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006325 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 }
6327 }
Robert Carr4e670e52018-08-15 13:26:12 -07006328
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006329 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330}
6331
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006332std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006333 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006334 if (connection == nullptr) {
6335 return "<nullptr>";
6336 }
6337 return connection->getInputChannelName();
6338}
6339
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006340void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006341 mAnrTracker.eraseToken(connection->getToken());
6342 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006343}
6344
Prabir Pradhancef936d2021-07-21 16:17:52 +00006345void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006346 const std::shared_ptr<Connection>& connection,
6347 uint32_t seq, bool handled,
6348 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006349 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006350 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006351
6352 { // Start critical section
6353 auto dispatchEntryIt =
6354 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6355 [seq](auto& e) { return e->seq == seq; });
6356 if (dispatchEntryIt == connection->waitQueue.end()) {
6357 return;
6358 }
6359
6360 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6361
6362 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6363 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006364 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006365 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6366 }
6367 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006368 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006369 dispatchEntry.deliveryTime, consumeTime, finishTime);
6370 }
6371
6372 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006373 fallbackKeyEntry =
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006374 afterKeyEventLockedInterruptable(connection, &dispatchEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006375 }
6376 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006377
6378 // Dequeue the event and start the next cycle.
6379 // Because the lock might have been released, it is possible that the
6380 // contents of the wait queue to have been drained, so we need to double-check
6381 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006382 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6383 [seq](auto& e) { return e->seq == seq; });
6384 if (entryIt != connection->waitQueue.end()) {
6385 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6386 connection->waitQueue.erase(entryIt);
6387
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006388 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006389 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6390 if (!connection->responsive) {
6391 connection->responsive = isConnectionResponsive(*connection);
6392 if (connection->responsive) {
6393 // The connection was unresponsive, and now it's responsive.
6394 processConnectionResponsiveLocked(*connection);
6395 }
6396 }
6397 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006398 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006399 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6400 // Only dispatch fallbacks if there is a window for the connection.
6401 if (windowHandle != nullptr) {
6402 const auto inputTarget =
6403 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6404 dispatchEntry->targetFlags,
6405 fallbackKeyEntry->downTime);
6406 if (inputTarget.has_value()) {
6407 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6408 *inputTarget);
6409 }
6410 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006411 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006412 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006413 }
6414
6415 // Start the next dispatch cycle for this connection.
6416 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006417}
6418
Prabir Pradhancef936d2021-07-21 16:17:52 +00006419void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6420 const sp<IBinder>& newToken) {
6421 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6422 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006423 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006424 };
6425 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426}
6427
Prabir Pradhancef936d2021-07-21 16:17:52 +00006428void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6429 auto command = [this, token, x, y]() REQUIRES(mLock) {
6430 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006431 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006432 };
6433 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006434}
6435
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006436void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006437 if (connection == nullptr) {
6438 LOG_ALWAYS_FATAL("Caller must check for nullness");
6439 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006440 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6441 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006442 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006443 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006444 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006445 return;
6446 }
6447 /**
6448 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6449 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6450 * has changed. This could cause newer entries to time out before the already dispatched
6451 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6452 * processes the events linearly. So providing information about the oldest entry seems to be
6453 * most useful.
6454 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006455 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6456 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006457 std::string reason =
6458 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006459 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006460 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006461 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006462 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006463 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006464
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006465 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6466
6467 // Stop waking up for events on this connection, it is already unresponsive
6468 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006469}
6470
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006471void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6472 std::string reason =
6473 StringPrintf("%s does not have a focused window", application->getName().c_str());
6474 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006475
Yabin Cui8eb9c552023-06-08 18:05:07 +00006476 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006477 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006478 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006479 };
6480 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006481}
6482
chaviw98318de2021-05-19 16:45:23 -05006483void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006484 const std::string& reason) {
6485 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6486 updateLastAnrStateLocked(windowLabel, reason);
6487}
6488
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006489void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6490 const std::string& reason) {
6491 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006492 updateLastAnrStateLocked(windowLabel, reason);
6493}
6494
6495void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6496 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006498 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499 struct tm tm;
6500 localtime_r(&t, &tm);
6501 char timestr[64];
6502 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006503 mLastAnrState.clear();
6504 mLastAnrState += INDENT "ANR:\n";
6505 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006506 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6507 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006508 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509}
6510
Prabir Pradhancef936d2021-07-21 16:17:52 +00006511void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006512 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006513 const KeyEvent event = createKeyEvent(entry);
6514 nsecs_t delay = 0;
6515 { // release lock
6516 scoped_unlock unlock(mLock);
6517 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006518 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006519 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6520 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6521 std::to_string(t.duration().count()).c_str());
6522 }
6523 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524
6525 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006526 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006527 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006528 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006530 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006531 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533}
6534
Prabir Pradhancef936d2021-07-21 16:17:52 +00006535void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006536 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006537 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006538 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006539 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006540 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006541 };
6542 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006543}
6544
Prabir Pradhanedd96402022-02-15 01:46:16 -08006545void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006546 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006547 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006548 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006549 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006550 };
6551 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006552}
6553
6554/**
6555 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6556 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6557 * command entry to the command queue.
6558 */
6559void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6560 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006561 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006562 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006563 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006564 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006565 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006566 pid = findMonitorPidByTokenLocked(connectionToken);
6567 } else {
6568 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006569 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006570 reason.c_str());
6571 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6572 if (handle != nullptr) {
6573 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006574 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006575 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006576 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006577}
6578
6579/**
6580 * Tell the policy that a connection has become responsive so that it can stop ANR.
6581 */
6582void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006583 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006584 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006585 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006586 pid = findMonitorPidByTokenLocked(connectionToken);
6587 } else {
6588 // The connection is a window
6589 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6590 if (handle != nullptr) {
6591 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006592 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006593 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006594 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006595}
6596
Prabir Pradhan24047542023-11-02 17:14:59 +00006597std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006598 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry, bool handled) {
6599 // The dispatchEntry is currently valid, but it might point to a deleted object after we release
6600 // the lock. For simplicity, make copies of the data of interest here and assume that
6601 // 'dispatchEntry' is not valid after this section.
6602 // Hold a strong reference to the EventEntry to ensure it's valid for the duration of this
6603 // function, even if the DispatchEntry gets destroyed and releases its share of the ownership.
6604 std::shared_ptr<const EventEntry> eventEntry = dispatchEntry->eventEntry;
6605 const bool hasForegroundTarget = dispatchEntry->hasForegroundTarget();
6606 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(eventEntry));
6607 // To prevent misuse, ensure dispatchEntry is no longer valid.
6608 dispatchEntry = nullptr;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006609 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006610 if (!handled) {
6611 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006612 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006613 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006614 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006617 // Get the fallback key state.
6618 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006619 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006620 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006621 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006622 connection->inputState.removeFallbackKey(originalKeyCode);
6623 }
6624
Siarhei Vishniakouf50323a2024-05-29 08:52:08 -07006625 if (handled || !hasForegroundTarget) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006626 // If the application handles the original key for which we previously
6627 // generated a fallback or if the window is not a foreground window,
6628 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006630 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006631 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6632 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6633 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6634 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6635 keyEntry.policyFlags);
6636 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006637 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006638 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639
6640 mLock.unlock();
6641
Prabir Pradhana41d2442023-04-20 21:30:40 +00006642 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006643 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6644 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006645 unhandledKeyFallback) {
6646 event = *unhandledKeyFallback;
6647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006648
6649 mLock.lock();
6650
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006651 // Cancel the fallback key, but only if we still have a window for the channel.
6652 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006653 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006654 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6655 if (windowHandle != nullptr) {
6656 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6657 "application handled the original non-fallback key "
6658 "or is no longer a foreground target, "
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006659 "canceling previously dispatched fallback key",
6660 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006661 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006662 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006664 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006665 connection->inputState.removeFallbackKey(originalKeyCode);
6666 }
6667 } else {
6668 // If the application did not handle a non-fallback key, first check
6669 // that we are in a good state to perform unhandled key event processing
6670 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006671 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006672 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006673 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6674 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6675 "since this is not an initial down. "
6676 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6677 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6678 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006679 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006682 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006683 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6684 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6685 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6686 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6687 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006688 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006689
6690 mLock.unlock();
6691
Prabir Pradhana41d2442023-04-20 21:30:40 +00006692 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006693 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6694 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006695 fb) {
6696 fallback = true;
6697 event = *fb;
6698 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006699
6700 mLock.lock();
6701
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006702 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006703 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006704 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006705 }
6706
6707 // Latch the fallback keycode for this key on an initial down.
6708 // The fallback keycode cannot change at any other point in the lifecycle.
6709 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006710 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006711 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006712 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006713 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006714 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006715 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006716 }
6717
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006718 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006719
6720 // Cancel the fallback key if the policy decides not to send it anymore.
6721 // We will continue to dispatch the key to the policy but we will no
6722 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006723 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6724 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006725 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6726 if (fallback) {
6727 ALOGD("Unhandled key event: Policy requested to send key %d"
6728 "as a fallback for %d, but on the DOWN it had requested "
6729 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006730 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006731 } else {
6732 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6733 "but on the DOWN it had requested to send %d. "
6734 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006735 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006736 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006737 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006738
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006739 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6740 if (windowHandle != nullptr) {
6741 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006742 "canceling fallback, policy no longer desires it",
6743 keyEntry.traceTracker);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006744 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006745 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006746 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006747
6748 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006749 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006750 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006751 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006752 }
6753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006754
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006755 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6756 {
6757 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006758 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006759 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006760 for (const auto& [key, value] : fallbackKeys) {
6761 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006762 }
6763 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6764 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006766 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006767
6768 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006769 // Return the fallback key that we want dispatched to the channel.
6770 std::unique_ptr<KeyEntry> newEntry =
6771 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6772 event.getEventTime(), event.getDeviceId(),
6773 event.getSource(), event.getDisplayId(),
6774 keyEntry.policyFlags, keyEntry.action,
6775 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6776 *fallbackKeyCode, event.getScanCode(),
6777 event.getMetaState(), event.getRepeatCount(),
6778 event.getDownTime());
Prabir Pradhana67623c2024-02-21 06:57:36 +00006779 if (mTracer) {
6780 newEntry->traceTracker =
6781 mTracer->traceDerivedEvent(*newEntry, *keyEntry.traceTracker);
6782 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006783 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6784 ALOGD("Unhandled key event: Dispatching fallback key. "
6785 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006786 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006787 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006788 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006789 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006790 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6791 ALOGD("Unhandled key event: No fallback key.");
6792 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006793
6794 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006795 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006796 }
6797 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006798 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006799}
6800
Michael Wrightd02c5b62014-02-10 15:10:22 -08006801void InputDispatcher::traceInboundQueueLengthLocked() {
6802 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006803 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006804 }
6805}
6806
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006807void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006808 if (ATRACE_ENABLED()) {
6809 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006810 snprintf(counterName, sizeof(counterName), "oq:%s",
6811 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006812 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006813 }
6814}
6815
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006816void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006817 if (ATRACE_ENABLED()) {
6818 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006819 snprintf(counterName, sizeof(counterName), "wq:%s",
6820 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006821 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822 }
6823}
6824
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006825void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006826 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006827
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006828 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006829 dumpDispatchStateLocked(dump);
6830
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006831 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006832 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006833 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006834 }
6835}
6836
6837void InputDispatcher::monitor() {
6838 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006839 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006840 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006841 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006842}
6843
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006844/**
6845 * Wake up the dispatcher and wait until it processes all events and commands.
6846 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6847 * this method can be safely called from any thread, as long as you've ensured that
6848 * the work you are interested in completing has already been queued.
6849 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006850bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006851 /**
6852 * Timeout should represent the longest possible time that a device might spend processing
6853 * events and commands.
6854 */
6855 constexpr std::chrono::duration TIMEOUT = 100ms;
6856 std::unique_lock lock(mLock);
6857 mLooper->wake();
6858 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6859 return result == std::cv_status::no_timeout;
6860}
6861
Vishnu Naire798b472020-07-23 13:52:21 -07006862/**
6863 * Sets focus to the window identified by the token. This must be called
6864 * after updating any input window handles.
6865 *
6866 * Params:
6867 * request.token - input channel token used to identify the window that should gain focus.
6868 * request.focusedToken - the token that the caller expects currently to be focused. If the
6869 * specified token does not match the currently focused window, this request will be dropped.
6870 * If the specified focused token matches the currently focused window, the call will succeed.
6871 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6872 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6873 * when requesting the focus change. This determines which request gets
6874 * precedence if there is a focus change request from another source such as pointer down.
6875 */
Vishnu Nair958da932020-08-21 17:12:37 -07006876void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6877 { // acquire lock
6878 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006879 std::optional<FocusResolver::FocusChanges> changes =
Linnan Li13bf76a2024-05-05 19:18:02 +08006880 mFocusResolver.setFocusedWindow(request,
6881 getWindowHandlesLocked(
6882 ui::LogicalDisplayId{request.displayId}));
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006883 ScopedSyntheticEventTracer traceContext(mTracer);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006884 if (changes) {
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006885 onFocusChangedLocked(*changes, traceContext.getTracker());
Vishnu Nair958da932020-08-21 17:12:37 -07006886 }
6887 } // release lock
6888 // Wake up poll loop since it may need to make new input dispatching choices.
6889 mLooper->wake();
6890}
6891
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006892void InputDispatcher::onFocusChangedLocked(
6893 const FocusResolver::FocusChanges& changes,
6894 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker,
6895 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006896 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006897 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6898 ? removedFocusedWindowHandle
6899 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6900 if (resolvedWindow == nullptr) {
6901 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006902 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006903 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00006904 "focus left window", traceTracker);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006905 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6906 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006907 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006908 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006909 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006910 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006911 }
6912
Vishnu Nairc519ff72021-01-21 08:23:08 -08006913 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhan9d3d5612024-06-06 20:34:26 +00006914 // If a window has pointer capture, then it must have focus and must be on the top-focused
6915 // display. We need to ensure that this contract is upheld when pointer capture is being
6916 // disabled due to a loss of window focus. If the window loses focus before it loses pointer
6917 // capture, then the window can be in a state where it has pointer capture but not focus,
6918 // violating the contract. Therefore we must dispatch the pointer capture event before the
6919 // focus event. Since focus events are added to the front of the queue (above), we add the
6920 // pointer capture event to the front of the queue after the focus events are added. This
6921 // ensures the pointer capture event ends up at the front.
6922 disablePointerCaptureForcedLocked();
6923
Prabir Pradhancef936d2021-07-21 16:17:52 +00006924 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006925 }
6926}
Vishnu Nair958da932020-08-21 17:12:37 -07006927
Prabir Pradhan99987712020-11-10 18:43:05 -08006928void InputDispatcher::disablePointerCaptureForcedLocked() {
Hiroki Sato25040232024-02-22 17:21:22 +09006929 if (!mCurrentPointerCaptureRequest.isEnable() && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006930 return;
6931 }
6932
6933 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6934
Hiroki Sato25040232024-02-22 17:21:22 +09006935 if (mCurrentPointerCaptureRequest.isEnable()) {
6936 setPointerCaptureLocked(nullptr);
Prabir Pradhan99987712020-11-10 18:43:05 -08006937 }
6938
6939 if (!mWindowTokenWithPointerCapture) {
6940 // No need to send capture changes because no window has capture.
6941 return;
6942 }
6943
6944 if (mPendingEvent != nullptr) {
6945 // Move the pending event to the front of the queue. This will give the chance
6946 // for the pending event to be dropped if it is a captured event.
6947 mInboundQueue.push_front(mPendingEvent);
6948 mPendingEvent = nullptr;
6949 }
6950
6951 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006952 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006953 mInboundQueue.push_front(std::move(entry));
6954}
6955
Hiroki Sato25040232024-02-22 17:21:22 +09006956void InputDispatcher::setPointerCaptureLocked(const sp<IBinder>& windowToken) {
6957 mCurrentPointerCaptureRequest.window = windowToken;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006958 mCurrentPointerCaptureRequest.seq++;
6959 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006960 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006961 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006962 };
6963 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006964}
6965
Linnan Li13bf76a2024-05-05 19:18:02 +08006966void InputDispatcher::displayRemoved(ui::LogicalDisplayId displayId) {
Vishnu Nair599f1412021-06-21 10:39:58 -07006967 { // acquire lock
6968 std::scoped_lock _l(mLock);
6969 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006970 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006971 setFocusedApplicationLocked(displayId, nullptr);
6972 // Call focus resolver to clean up stale requests. This must be called after input windows
6973 // have been removed for the removed display.
6974 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006975 // Reset pointer capture eligibility, regardless of previous state.
6976 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006977 // Remove the associated touch mode state.
6978 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006979 mVerifiersByDisplay.erase(displayId);
Siarhei Vishniakou870f4e72024-05-10 20:59:35 +00006980 mInputFilterVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006981 } // release lock
6982
6983 // Wake up poll loop since it may need to make new input dispatching choices.
6984 mLooper->wake();
6985}
6986
Patrick Williamsd828f302023-04-28 17:52:08 -05006987void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006988 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6989 {
6990 // acquire lock
6991 std::scoped_lock _l(mLock);
6992 logDispatchStateLocked();
6993 }
6994 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6995 result.error().message().c_str());
6996 };
chaviw15fab6f2021-06-07 14:15:52 -05006997 // The listener sends the windows as a flattened array. Separate the windows by display for
6998 // more convenient parsing.
Linnan Li13bf76a2024-05-05 19:18:02 +08006999 std::unordered_map<ui::LogicalDisplayId, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05007000 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05007001 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007002 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05007003 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007004
7005 { // acquire lock
7006 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00007007
7008 // Ensure that we have an entry created for all existing displays so that if a displayId has
7009 // no windows, we can tell that the windows were removed from the display.
7010 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
7011 handlesPerDisplay[displayId];
7012 }
7013
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007014 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05007015 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007016 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
7017 }
7018
7019 for (const auto& [displayId, handles] : handlesPerDisplay) {
7020 setInputWindowsLocked(handles, displayId);
7021 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05007022
7023 if (update.vsyncId < mWindowInfosVsyncId) {
7024 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
7025 ", current update vsync id: %" PRId64,
7026 mWindowInfosVsyncId, update.vsyncId);
7027 }
7028 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07007029 }
7030 // Wake up poll loop since it may need to make new input dispatching choices.
7031 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05007032}
7033
Vishnu Nair062a8672021-09-03 16:07:44 -07007034bool InputDispatcher::shouldDropInput(
7035 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007036 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
7037 (windowHandle->getInfo()->inputConfig.test(
7038 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07007039 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007040 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
Linnan Li13bf76a2024-05-05 19:18:02 +08007041 "display %s.",
Vishnu Nair062a8672021-09-03 16:07:44 -07007042 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007043 windowHandle->getInfo()->inputConfig.string().c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08007044 windowHandle->getInfo()->displayId.toString().c_str());
Vishnu Nair062a8672021-09-03 16:07:44 -07007045 return true;
7046 }
7047 return false;
7048}
7049
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007050void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05007051 const gui::WindowInfosUpdate& update) {
7052 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07007053}
7054
Arthur Hungdfd528e2021-12-08 13:23:04 +00007055void InputDispatcher::cancelCurrentTouch() {
7056 {
7057 std::scoped_lock _l(mLock);
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007058 ScopedSyntheticEventTracer traceContext(mTracer);
Arthur Hungdfd528e2021-12-08 13:23:04 +00007059 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00007060 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007061 "cancel current touch", traceContext.getTracker());
Arthur Hungdfd528e2021-12-08 13:23:04 +00007062 synthesizeCancelationEventsForAllConnectionsLocked(options);
7063
7064 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00007065 }
7066 // Wake up poll loop since there might be work to do.
7067 mLooper->wake();
7068}
7069
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007070void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
7071 std::scoped_lock _l(mLock);
7072 mMonitorDispatchingTimeout = timeout;
7073}
7074
Arthur Hungc539dbb2022-12-08 07:45:36 +00007075void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
7076 const sp<WindowInfoHandle>& oldWindowHandle,
7077 const sp<WindowInfoHandle>& newWindowHandle,
Linnan Li72352222024-04-12 18:55:57 +08007078 TouchState& state, DeviceId deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007079 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07007080 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007081 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00007082 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
7083 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7084 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
7085 newWindowHandle->getInfo()->inputConfig.test(
7086 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7087 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007088 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007089 const sp<WindowInfoHandle> newWallpaper =
7090 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
7091 if (oldWallpaper == newWallpaper) {
7092 return;
7093 }
7094
7095 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08007096 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007097 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007098 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007099 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007100 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007101 }
7102
7103 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007104 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
7105 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00007106 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007107 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007108 }
7109}
7110
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007111void InputDispatcher::transferWallpaperTouch(
7112 ftl::Flags<InputTarget::Flags> oldTargetFlags,
7113 ftl::Flags<InputTarget::Flags> newTargetFlags, const sp<WindowInfoHandle> fromWindowHandle,
Linnan Li72352222024-04-12 18:55:57 +08007114 const sp<WindowInfoHandle> toWindowHandle, TouchState& state, DeviceId deviceId,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007115 const std::vector<PointerProperties>& pointers,
7116 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00007117 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7118 fromWindowHandle->getInfo()->inputConfig.test(
7119 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7120 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7121 toWindowHandle->getInfo()->inputConfig.test(
7122 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7123
7124 const sp<WindowInfoHandle> oldWallpaper =
Linnan Li72352222024-04-12 18:55:57 +08007125 oldHasWallpaper ? state.getWallpaperWindow(deviceId) : nullptr;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007126 const sp<WindowInfoHandle> newWallpaper =
7127 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
7128 if (oldWallpaper == newWallpaper) {
7129 return;
7130 }
7131
7132 if (oldWallpaper != nullptr) {
7133 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007134 "transferring touch focus to another window", traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007135 state.removeWindowByToken(oldWallpaper->getToken());
7136 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7137 }
7138
7139 if (newWallpaper != nullptr) {
7140 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007141 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7142 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007143 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7144 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007145 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007146 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007147 std::shared_ptr<Connection> wallpaperConnection =
7148 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007149 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007150 std::shared_ptr<Connection> toConnection =
7151 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007152 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7153 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
Prabir Pradhand6b2b052024-02-21 23:25:15 +00007154 wallpaperFlags, traceTracker);
Arthur Hungc539dbb2022-12-08 07:45:36 +00007155 }
7156 }
7157}
7158
7159sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7160 const sp<WindowInfoHandle>& windowHandle) const {
7161 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7162 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7163 bool foundWindow = false;
7164 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7165 if (!foundWindow && otherHandle != windowHandle) {
7166 continue;
7167 }
7168 if (windowHandle == otherHandle) {
7169 foundWindow = true;
7170 continue;
7171 }
7172
7173 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7174 return otherHandle;
7175 }
7176 }
7177 return nullptr;
7178}
7179
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007180void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7181 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007182 std::scoped_lock _l(mLock);
7183
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007184 mConfig.keyRepeatTimeout = timeout.count();
7185 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007186}
7187
Linnan Li13bf76a2024-05-05 19:18:02 +08007188bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token,
7189 ui::LogicalDisplayId displayId, DeviceId deviceId,
7190 int32_t pointerId) {
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007191 std::scoped_lock _l(mLock);
7192 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7193 if (touchStateIt == mTouchStatesByDisplay.end()) {
7194 return false;
7195 }
7196 for (const TouchedWindow& window : touchStateIt->second.windows) {
7197 if (window.windowHandle->getToken() == token &&
7198 (window.hasTouchingPointer(deviceId, pointerId) ||
7199 window.hasHoveringPointer(deviceId, pointerId))) {
7200 return true;
7201 }
7202 }
7203 return false;
7204}
7205
Prabir Pradhan04a66422024-03-15 22:45:27 +00007206void InputDispatcher::setInputMethodConnectionIsActive(bool isActive) {
7207 std::scoped_lock _l(mLock);
7208 if (mTracer) {
7209 mTracer->setInputMethodConnectionIsActive(isActive);
7210 }
7211}
7212
Garfield Tane84e6f92019-08-29 17:28:41 -07007213} // namespace android::inputdispatcher