blob: 7f54bf1945ba037c6575dfde08efbfd50e070b9e [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000057#include "trace/ThreadedBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62#define INDENT4 " "
63
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080064using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070065using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080066using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000067using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070069using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050070using android::gui::FocusRequest;
71using android::gui::TouchOcclusionMode;
72using android::gui::WindowInfo;
73using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080074using android::os::InputEventInjectionResult;
75using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000076namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000081
Prabir Pradhandae52792023-12-15 07:36:40 +000082// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
83// flag is enabled. When the flag is changed, tracing will only be available after reboot.
84bool isInputTracingEnabled() {
85 static const std::string buildType = base::GetProperty("ro.build.type", "user");
86 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
87 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
88}
89
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000090// Create the input tracing backend that writes to perfetto from a single thread.
91std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
92 if (!isInputTracingEnabled()) {
93 return nullptr;
94 }
95 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
96 trace::impl::PerfettoBackend());
97}
98
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000099template <class Entry>
100void ensureEventTraced(const Entry& entry) {
101 if (!entry.traceTracker) {
102 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
103 }
104}
105
Prabir Pradhancef936d2021-07-21 16:17:52 +0000106// Temporarily releases a held mutex for the lifetime of the instance.
107// Named to match std::scoped_lock
108class scoped_unlock {
109public:
110 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
111 ~scoped_unlock() { mMutex.lock(); }
112
113private:
114 std::mutex& mMutex;
115};
116
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117// Default input dispatching timeout if there is no focused application or paused window
118// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800119const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
120 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
121 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800123// The default minimum time gap between two user activity poke events.
124const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
125
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800126const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128// 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 +0000129constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
130
131// Log a warning when an interception call takes longer than this to process.
132constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133
134// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000135constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
136
Antonio Kantekea47acb2021-12-23 12:41:25 -0800137// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000138constexpr int LOGTAG_INPUT_INTERACTION = 62000;
139constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000140constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000141
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000142const ui::Transform kIdentityTransform;
143
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000144inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 return systemTime(SYSTEM_TIME_MONOTONIC);
146}
147
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700148inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000149 if (binder == nullptr) {
150 return "<null>";
151 }
152 return StringPrintf("%p", binder.get());
153}
154
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000155static std::string uidString(const gui::Uid& uid) {
156 return uid.toString();
157}
158
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AKEY_EVENT_ACTION_DOWN:
162 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700165 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 }
167}
168
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700169Result<void> validateKeyEvent(int32_t action) {
170 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171}
172
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700176 case AMOTION_EVENT_ACTION_UP: {
177 if (pointerCount != 1) {
178 return Error() << "invalid pointer count " << pointerCount;
179 }
180 return {};
181 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 case AMOTION_EVENT_ACTION_HOVER_ENTER:
184 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700185 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
186 if (pointerCount < 1) {
187 return Error() << "invalid pointer count " << pointerCount;
188 }
189 return {};
190 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800191 case AMOTION_EVENT_ACTION_CANCEL:
192 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700194 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800197 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700198 if (index < 0) {
199 return Error() << "invalid index " << index << " for "
200 << MotionEvent::actionToString(action);
201 }
202 if (index >= pointerCount) {
203 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
204 }
205 if (pointerCount <= 1) {
206 return Error() << "invalid pointer count " << pointerCount << " for "
207 << MotionEvent::actionToString(action);
208 }
209 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700210 }
211 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700212 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
213 if (actionButton == 0) {
214 return Error() << "action button should be nonzero for "
215 << MotionEvent::actionToString(action);
216 }
217 return {};
218 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700219 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
222}
223
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000224int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500225 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
226}
227
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700228Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
229 const PointerProperties* pointerProperties) {
230 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
231 if (!actionCheck.ok()) {
232 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
234 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700235 return Error() << "Motion event has invalid pointer count " << pointerCount
236 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800238 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 for (size_t i = 0; i < pointerCount; i++) {
240 int32_t id = pointerProperties[i].id;
241 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700242 return Error() << "Motion event has invalid pointer id " << id
243 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800245 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700246 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800248 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700250 return {};
251}
252
253Result<void> validateInputEvent(const InputEvent& event) {
254 switch (event.getType()) {
255 case InputEventType::KEY: {
256 const KeyEvent& key = static_cast<const KeyEvent&>(event);
257 const int32_t action = key.getAction();
258 return validateKeyEvent(action);
259 }
260 case InputEventType::MOTION: {
261 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
262 const int32_t action = motion.getAction();
263 const size_t pointerCount = motion.getPointerCount();
264 const PointerProperties* pointerProperties = motion.getPointerProperties();
265 const int32_t actionButton = motion.getActionButton();
266 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
267 }
268 default: {
269 return {};
270 }
271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800274std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
275 std::bitset<MAX_POINTER_ID + 1> pointerIds;
276 for (const PointerProperties& pointer : pointers) {
277 pointerIds.set(pointer.id);
278 }
279 return pointerIds;
280}
281
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000282std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000284 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 }
286
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000287 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 bool first = true;
289 Region::const_iterator cur = region.begin();
290 Region::const_iterator const tail = region.end();
291 while (cur != tail) {
292 if (first) {
293 first = false;
294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800295 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800297 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298 cur++;
299 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000300 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301}
302
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000303std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
304 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500305 constexpr size_t maxEntries = 50; // max events to print
306 constexpr size_t skipBegin = maxEntries / 2;
307 const size_t skipEnd = queue.size() - maxEntries / 2;
308 // skip from maxEntries / 2 ... size() - maxEntries/2
309 // only print from 0 .. skipBegin and then from skipEnd .. size()
310
311 std::string dump;
312 for (size_t i = 0; i < queue.size(); i++) {
313 const DispatchEntry& entry = *queue[i];
314 if (i >= skipBegin && i < skipEnd) {
315 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
316 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
317 continue;
318 }
319 dump.append(INDENT4);
320 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000321 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
322 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500323 ns2ms(currentTime - entry.eventEntry->eventTime));
324 if (entry.deliveryTime != 0) {
325 // This entry was delivered, so add information on how long we've been waiting
326 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
327 }
328 dump.append("\n");
329 }
330 return dump;
331}
332
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333/**
334 * Find the entry in std::unordered_map by key, and return it.
335 * If the entry is not found, return a default constructed entry.
336 *
337 * Useful when the entries are vectors, since an empty vector will be returned
338 * if the entry is not found.
339 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
340 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700341template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700343 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700344 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800345}
346
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000347bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700348 if (first == second) {
349 return true;
350 }
351
352 if (first == nullptr || second == nullptr) {
353 return false;
354 }
355
356 return first->getToken() == second->getToken();
357}
358
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000359bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000360 if (first == nullptr || second == nullptr) {
361 return false;
362 }
363 return first->applicationInfo.token != nullptr &&
364 first->applicationInfo.token == second->applicationInfo.token;
365}
366
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800367template <typename T>
368size_t firstMarkedBit(T set) {
369 // TODO: replace with std::countr_zero from <bit> when that's available
370 LOG_ALWAYS_FATAL_IF(set.none());
371 size_t i = 0;
372 while (!set.test(i)) {
373 i++;
374 }
375 return i;
376}
377
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000378std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
379 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000380 std::shared_ptr<const EventEntry> eventEntry,
381 ftl::Flags<InputTarget::Flags> inputTargetFlags,
382 int64_t vsyncId) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000383 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000384 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
385 const std::optional<int32_t> windowId =
386 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
387 // Assume the only targets that are not associated with a window are global monitors, and use
388 // the system UID for global monitors for tracing purposes.
389 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000390
391 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700392 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700393 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700394 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000395 inputTarget.globalScaleFactor, uid, vsyncId,
396 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000397 }
398
399 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
400 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
401
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000402 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000404 const ui::Transform* transform = &kIdentityTransform;
405 const ui::Transform* displayTransform = &kIdentityTransform;
406 if (zeroCoords) {
407 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
408 } else {
409 // Use the first pointer information to normalize all other pointers. This could be any
410 // pointer as long as all other pointers are normalized to the same value and the final
411 // DispatchEntry uses the transform for the normalized pointer.
412 transform =
413 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
414 const ui::Transform inverseTransform = transform->inverse();
415 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000416
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000417 // Iterate through all pointers in the event to normalize against the first.
418 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
419 PointerCoords& newCoords = pointerCoords[i];
420 const auto pointerId = motionEntry.pointerProperties[i].id;
421 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000422
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000423 newCoords.copyFrom(motionEntry.pointerCoords[i]);
424 // First, apply the current pointer's transform to update the coordinates into
425 // window space.
426 newCoords.transform(currTransform);
427 // Next, apply the inverse transform of the normalized coordinates so the
428 // current coordinates are transformed into the normalized coordinate space.
429 newCoords.transform(inverseTransform);
430 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431 }
432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700433 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000434 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000435 motionEntry.eventTime, motionEntry.deviceId,
436 motionEntry.source, motionEntry.displayId,
437 motionEntry.policyFlags, motionEntry.action,
438 motionEntry.actionButton, motionEntry.flags,
439 motionEntry.metaState, motionEntry.buttonState,
440 motionEntry.classification, motionEntry.edgeFlags,
441 motionEntry.xPrecision, motionEntry.yPrecision,
442 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
443 motionEntry.downTime, motionEntry.pointerProperties,
444 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000445
446 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700447 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000448 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000449 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000450 return dispatchEntry;
451}
452
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500453template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500455 if (lhs == nullptr && rhs == nullptr) {
456 return true;
457 }
458 if (lhs == nullptr || rhs == nullptr) {
459 return false;
460 }
461 return *lhs == *rhs;
462}
463
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000464KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000465 KeyEvent event;
466 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
467 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
468 entry.repeatCount, entry.downTime, entry.eventTime);
469 return event;
470}
471
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000472bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000473 // Do not keep track of gesture monitors. They receive every event and would disproportionately
474 // affect the statistics.
475 if (connection.monitor) {
476 return false;
477 }
478 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
479 if (!connection.responsive) {
480 return false;
481 }
482 return true;
483}
484
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000485bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000486 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
487 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000488 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
489 return false;
490 }
491 // Only track latency for events that originated from hardware
492 if (eventEntry.isSynthesized()) {
493 return false;
494 }
495 const EventEntry::Type& inputEventEntryType = eventEntry.type;
496 if (inputEventEntryType == EventEntry::Type::KEY) {
497 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
498 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
499 return false;
500 }
501 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
502 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
503 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
504 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
505 return false;
506 }
507 } else {
508 // Not a key or a motion
509 return false;
510 }
511 if (!shouldReportMetricsForConnection(connection)) {
512 return false;
513 }
514 return true;
515}
516
Prabir Pradhancef936d2021-07-21 16:17:52 +0000517/**
518 * Connection is responsive if it has no events in the waitQueue that are older than the
519 * current time.
520 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000521bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000522 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000523 for (const auto& dispatchEntry : connection.waitQueue) {
524 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000525 return false;
526 }
527 }
528 return true;
529}
530
Antonio Kantekf16f2832021-09-28 04:39:20 +0000531// Returns true if the event type passed as argument represents a user activity.
532bool isUserActivityEvent(const EventEntry& eventEntry) {
533 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000534 case EventEntry::Type::CONFIGURATION_CHANGED:
535 case EventEntry::Type::DEVICE_RESET:
536 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000537 case EventEntry::Type::FOCUS:
538 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000539 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000540 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000541 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000542 case EventEntry::Type::KEY:
543 case EventEntry::Type::MOTION:
544 return true;
545 }
546}
547
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000549bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000550 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800551 const auto inputConfig = windowInfo.inputConfig;
552 if (windowInfo.displayId != displayId ||
553 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800554 return false;
555 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700556 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800557 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800558 return false;
559 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000560
561 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
562 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
563 // the window. Points on the right and bottom edges should not be inside the window, so we need
564 // to be careful about performing a hit test when the display is rotated, since the "right" and
565 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
566 // logical display in which WM determined the bounds. Perform the hit test in the logical
567 // display space to ensure these edges are considered correctly in all orientations.
568 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
569 const auto p = displayTransform.transform(x, y);
570 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800571 return false;
572 }
573 return true;
574}
575
Prabir Pradhand65552b2021-10-07 11:23:50 -0700576bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
577 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000578 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700579}
580
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800581// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000582// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
583// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
584// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800585// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000586bool canReceiveForegroundTouches(const WindowInfo& info) {
587 // A non-touchable window can still receive touch events (e.g. in the case of
588 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
589 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
590}
591
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000592bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700593 if (windowHandle == nullptr) {
594 return false;
595 }
596 const WindowInfo* windowInfo = windowHandle->getInfo();
597 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
598 return true;
599 }
600 return false;
601}
602
Prabir Pradhan5735a322022-04-11 17:23:34 +0000603// Checks targeted injection using the window's owner's uid.
604// Returns an empty string if an entry can be sent to the given window, or an error message if the
605// entry is a targeted injection whose uid target doesn't match the window owner.
606std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
607 const EventEntry& entry) {
608 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
609 // The event was not injected, or the injected event does not target a window.
610 return {};
611 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000612 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000613 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000614 return StringPrintf("No valid window target for injection into uid %s.",
615 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000616 }
617 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000618 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
619 "owned by uid %s.",
620 uid.toString().c_str(), window->getName().c_str(),
621 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000622 }
623 return {};
624}
625
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000626std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700627 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
628 // Always dispatch mouse events to cursor position.
629 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000630 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700631 }
632
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700633 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000634 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
635 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700636}
637
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700638std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
639 if (eventEntry.type == EventEntry::Type::KEY) {
640 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
641 return keyEntry.downTime;
642 } else if (eventEntry.type == EventEntry::Type::MOTION) {
643 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
644 return motionEntry.downTime;
645 }
646 return std::nullopt;
647}
648
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000649/**
650 * Compare the old touch state to the new touch state, and generate the corresponding touched
651 * windows (== input targets).
652 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
653 * If the pointer just entered the new window, produce HOVER_ENTER.
654 * For pointers remaining in the window, produce HOVER_MOVE.
655 */
656std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
657 const TouchState& newTouchState,
658 const MotionEntry& entry) {
659 std::vector<TouchedWindow> out;
660 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700661
662 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
663 // ACTION_SCROLL events should not affect the hovering pointer dispatch
664 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000665 }
666
667 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800668 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000669
670 std::set<sp<WindowInfoHandle>> oldWindows;
671 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800672 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 }
674
675 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800676 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677
678 // If the pointer is no longer in the new window set, send HOVER_EXIT.
679 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
680 if (newWindows.find(oldWindow) == newWindows.end()) {
681 TouchedWindow touchedWindow;
682 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000683 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 out.push_back(touchedWindow);
685 }
686 }
687
688 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
689 TouchedWindow touchedWindow;
690 touchedWindow.windowHandle = newWindow;
691 if (oldWindows.find(newWindow) == oldWindows.end()) {
692 // Any windows that have this pointer now, and didn't have it before, should get
693 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000694 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000695 } else {
696 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700697 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700698 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000699 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
700 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700701 // The Accessibility injected touch exploration event stream
702 // has known inconsistencies, so log ERROR instead of
703 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700704 severity = android::base::LogSeverity::ERROR;
705 }
706 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700707 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000708 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000709 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800710 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000711 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
712 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
713 }
714 out.push_back(touchedWindow);
715 }
716 return out;
717}
718
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800719template <typename T>
720std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
721 left.insert(left.end(), right.begin(), right.end());
722 return left;
723}
724
Harry Cuttsb166c002023-05-09 13:06:05 +0000725// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
726// both.
727void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
728 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
729 if (!window.windowHandle->getInfo()->inputConfig.test(
730 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
731 // In addition to TouchState, erase this window from the input targets! We don't have a
732 // good way to do this today except by adding a nested loop.
733 // TODO(b/282025641): simplify this code once InputTargets are being identified
734 // separately from TouchedWindows.
735 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800736 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000737 });
738 return true;
739 }
740 return false;
741 });
742}
743
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700744/**
745 * In general, touch should be always split between windows. Some exceptions:
746 * 1. Don't split touch if all of the below is true:
747 * (a) we have an active pointer down *and*
748 * (b) a new pointer is going down that's from the same device *and*
749 * (c) the window that's receiving the current pointer does not support split touch.
750 * 2. Don't split mouse events
751 */
752bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
753 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
754 // We should never split mouse events
755 return false;
756 }
757 for (const TouchedWindow& touchedWindow : touchState.windows) {
758 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
759 // Spy windows should not affect whether or not touch is split.
760 continue;
761 }
762 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
763 continue;
764 }
765 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
766 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
767 // Wallpaper window should not affect whether or not touch is split
768 continue;
769 }
770
771 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
772 return false;
773 }
774 }
775 return true;
776}
777
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700778/**
779 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
780 */
781bool isStylusActiveInDisplay(
782 int32_t displayId,
783 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
784 const auto it = touchStatesByDisplay.find(displayId);
785 if (it == touchStatesByDisplay.end()) {
786 return false;
787 }
788 const TouchState& state = it->second;
789 return state.hasActiveStylus();
790}
791
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800792Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
793 struct HashFunction {
794 size_t operator()(const WindowInfo& info) const { return info.id; }
795 };
796
797 std::unordered_set<WindowInfo, HashFunction> windowSet;
798 for (const WindowInfo& info : update.windowInfos) {
799 const auto [_, inserted] = windowSet.insert(info);
800 if (!inserted) {
801 return Error() << "Duplicate entry for " << info;
802 }
803 }
804 return {};
805}
806
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800807int32_t getUserActivityEventType(const EventEntry& eventEntry) {
808 switch (eventEntry.type) {
809 case EventEntry::Type::KEY: {
810 return USER_ACTIVITY_EVENT_BUTTON;
811 }
812 case EventEntry::Type::MOTION: {
813 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
814 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
815 return USER_ACTIVITY_EVENT_TOUCH;
816 }
817 return USER_ACTIVITY_EVENT_OTHER;
818 }
819 default: {
820 LOG_ALWAYS_FATAL("%s events are not user activity",
821 ftl::enum_string(eventEntry.type).c_str());
822 }
823 }
824}
825
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000826std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
827 CancelationOptions::Mode mode) {
828 switch (mode) {
829 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
830 return {true, true};
831 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
832 return {true, false};
833 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
834 return {false, true};
835 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
836 return {false, true};
837 }
838}
839
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000840} // namespace
841
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842// --- InputDispatcher ---
843
Prabir Pradhana41d2442023-04-20 21:30:40 +0000844InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000845 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000846
847InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
848 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700849 : mPolicy(policy),
850 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800852 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800853 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700854 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800855 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700856 mDispatchEnabled(false),
857 mDispatchFrozen(false),
858 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100859 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000860 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800861 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000862 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000863 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700864 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800865 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700867 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700868#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700869 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700870#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700871 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000872
873 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000874 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000875 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800876
877 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
880InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000881 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882
Prabir Pradhancef936d2021-07-21 16:17:52 +0000883 resetKeyRepeatLocked();
884 releasePendingEventLocked();
885 drainInboundQueueLocked();
886 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000888 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700889 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800890 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892}
893
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700894status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700895 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700896 return ALREADY_EXISTS;
897 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700898 mThread = std::make_unique<InputThread>(
899 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
900 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700901}
902
903status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700904 if (mThread && mThread->isCallingThread()) {
905 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700906 return INVALID_OPERATION;
907 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700908 mThread.reset();
909 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700910}
911
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700913 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800915 std::scoped_lock _l(mLock);
916 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917
918 // Run a dispatch loop if there are no pending commands.
919 // The dispatch loop might enqueue commands to run afterwards.
920 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800921 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923
924 // Run all pending commands if there are any.
925 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000926 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700927 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 // If we are still waiting for ack on some events,
931 // we might have to wake up earlier to check if an app is anr'ing.
932 const nsecs_t nextAnrCheck = processAnrsLocked();
933 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
934
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800935 // We are about to enter an infinitely long sleep, because we have no commands or
936 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700937 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800938 mDispatcherEnteredIdle.notify_all();
939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 } // release lock
941
942 // Wait for callback or timeout or wake. (make sure we round up, not down)
943 nsecs_t currentTime = now();
944 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
945 mLooper->pollOnce(timeoutMillis);
946}
947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500949 * Raise ANR if there is no focused window.
950 * Before the ANR is raised, do a final state check:
951 * 1. The currently focused application must be the same one we are waiting for.
952 * 2. Ensure we still don't have a focused window.
953 */
954void InputDispatcher::processNoFocusedWindowAnrLocked() {
955 // Check if the application that we are waiting for is still focused.
956 std::shared_ptr<InputApplicationHandle> focusedApplication =
957 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
958 if (focusedApplication == nullptr ||
959 focusedApplication->getApplicationToken() !=
960 mAwaitedFocusedApplication->getApplicationToken()) {
961 // Unexpected because we should have reset the ANR timer when focused application changed
962 ALOGE("Waited for a focused window, but focused application has already changed to %s",
963 focusedApplication->getName().c_str());
964 return; // The focused application has changed.
965 }
966
chaviw98318de2021-05-19 16:45:23 -0500967 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500968 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
969 if (focusedWindowHandle != nullptr) {
970 return; // We now have a focused window. No need for ANR.
971 }
972 onAnrLocked(mAwaitedFocusedApplication);
973}
974
975/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700976 * Check if any of the connections' wait queues have events that are too old.
977 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
978 * Return the time at which we should wake up next.
979 */
980nsecs_t InputDispatcher::processAnrsLocked() {
981 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700982 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700983 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
984 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
985 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500986 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700987 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500988 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700989 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700990 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500991 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
993 }
994 }
995
996 // Check if any connection ANRs are due
997 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
998 if (currentTime < nextAnrCheck) { // most likely scenario
999 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1000 }
1001
1002 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001003 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 if (connection == nullptr) {
1005 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1006 return nextAnrCheck;
1007 }
1008 connection->responsive = false;
1009 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001010 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001011 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001012 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001013}
1014
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001015std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001016 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001017 if (connection->monitor) {
1018 return mMonitorDispatchingTimeout;
1019 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001020 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001021 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001022 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001023 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001024 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025}
1026
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001027void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 nsecs_t currentTime = now();
1029
Jeff Browndc5992e2014-04-11 01:27:26 -07001030 // Reset the key repeat timer whenever normal dispatch is suspended while the
1031 // device is in a non-interactive state. This is to ensure that we abort a key
1032 // repeat if the device is just coming out of sleep.
1033 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 resetKeyRepeatLocked();
1035 }
1036
1037 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1038 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001039 if (DEBUG_FOCUS) {
1040 ALOGD("Dispatch frozen. Waiting some more.");
1041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 return;
1043 }
1044
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 // Ready to start a new event.
1046 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 // Synthesize a key repeat if appropriate.
1050 if (mKeyRepeatState.lastKeyEntry) {
1051 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1052 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1053 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001054 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
1057
1058 // Nothing to do if there is no pending event.
1059 if (!mPendingEvent) {
1060 return;
1061 }
1062 } else {
1063 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 mPendingEvent = mInboundQueue.front();
1065 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 traceInboundQueueLengthLocked();
1067 }
1068
1069 // Poke user activity for this event.
1070 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001071 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074
1075 // Now we have an event to dispatch.
1076 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085
1086 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089
1090 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001091 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 const ConfigurationChangedEntry& typedEntry =
1093 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 break;
1097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001099 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const DeviceResetEntry& typedEntry =
1101 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 break;
1105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001107 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const FocusEntry> typedEntry =
1109 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001110 dispatchFocusLocked(currentTime, typedEntry);
1111 done = true;
1112 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1113 break;
1114 }
1115
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001116 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001118 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1119 done = true;
1120 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1121 break;
1122 }
1123
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1125 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001126 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1128 done = true;
1129 break;
1130 }
1131
arthurhungb89ccb02020-12-30 16:19:01 +08001132 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const DragEntry> typedEntry =
1134 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001135 dispatchDragLocked(currentTime, typedEntry);
1136 done = true;
1137 break;
1138 }
1139
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001141 std::shared_ptr<const KeyEntry> keyEntry =
1142 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1147 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001150 if (done && mTracer) {
1151 ensureEventTraced(*keyEntry);
1152 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1153 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 break;
1155 }
1156
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001158 std::shared_ptr<const MotionEntry> motionEntry =
1159 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001161 // The event is stale. However, only drop stale events if there isn't an ongoing
1162 // gesture. That would allow us to complete the processing of the current stroke.
1163 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1164 if (touchStateIt != mTouchStatesByDisplay.end()) {
1165 const TouchState& touchState = touchStateIt->second;
1166 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1167 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1168 dropReason = DropReason::STALE;
1169 }
1170 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001171 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001172 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001173 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1174 // Only drop events that are focus-dispatched.
1175 dropReason = DropReason::BLOCKED;
1176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001178 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001179 if (done && mTracer) {
1180 ensureEventTraced(*motionEntry);
1181 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1182 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
Chris Yef59a2f42020-10-16 12:55:26 -07001185
1186 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001187 std::shared_ptr<const SensorEntry> sensorEntry =
1188 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001189
Chris Yef59a2f42020-10-16 12:55:26 -07001190 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1191 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1192 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1193 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1194 dropReason = DropReason::STALE;
1195 }
1196 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1197 done = true;
1198 break;
1199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201
1202 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001203 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
Michael Wright3a981722015-06-10 15:26:13 +01001206 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
1208 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001209 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
1211}
1212
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001213bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001214 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001215}
1216
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001217/**
1218 * Return true if the events preceding this incoming motion event should be dropped
1219 * Return false otherwise (the default behaviour)
1220 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001221bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001222 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001223 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224
1225 // Optimize case where the current application is unresponsive and the user
1226 // decides to touch a window in a different application.
1227 // If the application takes too long to catch up then we drop all events preceding
1228 // the touch into the other window.
1229 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001230 const int32_t displayId = motionEntry.displayId;
1231 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001232 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001233
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001234 sp<WindowInfoHandle> touchedWindowHandle =
1235 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001236 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001237 touchedWindowHandle->getApplicationToken() !=
1238 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001239 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 ALOGI("Pruning input queue because user touched a different application while waiting "
1241 "for %s",
1242 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001243 return true;
1244 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001245
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001246 // Alternatively, maybe there's a spy window that could handle this event.
1247 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1248 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1249 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001250 const std::shared_ptr<Connection> connection =
1251 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001252 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001253 // This spy window could take more input. Drop all events preceding this
1254 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001255 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001256 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001257 mAwaitedFocusedApplication->getName().c_str());
1258 return true;
1259 }
1260 }
1261 }
1262
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001263 return false;
1264}
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001267 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001269 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 traceInboundQueueLengthLocked();
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001273 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001274 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1275 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001278 if (mTracer) {
1279 ensureEventTraced(keyEntry);
1280 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001281
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001282 // If a new up event comes in, and the pending event with same key code has been asked
1283 // to try again later because of the policy. We have to reset the intercept key wake up
1284 // time for it may have been handled in the policy and could be dropped.
1285 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1286 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001287 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001288 if (pendingKey.keyCode == keyEntry.keyCode &&
1289 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001290 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1291 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001292 pendingKey.interceptKeyWakeupTime = 0;
1293 needWake = true;
1294 }
1295 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 break;
1297 }
1298
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001299 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001300 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1301 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001302 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1303 if (mTracer) {
1304 ensureEventTraced(motionEntry);
1305 }
1306 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001310
1311 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1312 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1313 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1314 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1315 // and some other events have not yet been processed, the dispatcher will wait for
1316 // these events to be processed before dispatching the key event. This is because
1317 // the unprocessed events may cause the focus to change (for example, by launching a
1318 // new window or tapping a different window). To prevent waiting too long, we force
1319 // the key to be sent to the currently focused window when a new tap comes in.
1320 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1321 "just send the pending key event to the currently focused window.");
1322 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001323 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001324 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001327 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001328 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1329 break;
1330 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001331 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001332 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001333 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001334 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001335 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1336 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001337 // nothing to do
1338 break;
1339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341
1342 return needWake;
1343}
1344
Prabir Pradhan24047542023-11-02 17:14:59 +00001345void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001346 // Do not store sensor event in recent queue to avoid flooding the queue.
1347 if (entry->type != EventEntry::Type::SENSOR) {
1348 mRecentQueue.push_back(entry);
1349 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001350 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001351 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001355sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1356 bool isStylus,
1357 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001359 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001360 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001361 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001362 continue;
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001365 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001366 if (!info.isSpy() &&
1367 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 return windowHandle;
1369 }
1370 }
1371 return nullptr;
1372}
1373
1374std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001375 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001376 if (touchedWindow == nullptr) {
1377 return {};
1378 }
1379 // Traverse windows from front to back until we encounter the touched window.
1380 std::vector<InputTarget> outsideTargets;
1381 const auto& windowHandles = getWindowHandlesLocked(displayId);
1382 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1383 if (windowHandle == touchedWindow) {
1384 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1385 // below the touched window will not get ACTION_OUTSIDE event.
1386 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001387 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001388
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001389 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001390 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001391 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1392 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001393 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1394 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001395 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
1397 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001398 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399}
1400
Prabir Pradhand65552b2021-10-07 11:23:50 -07001401std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001402 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001403 // Traverse windows from front to back and gather the touched spy windows.
1404 std::vector<sp<WindowInfoHandle>> spyWindows;
1405 const auto& windowHandles = getWindowHandlesLocked(displayId);
1406 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1407 const WindowInfo& info = *windowHandle->getInfo();
1408
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001409 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001410 continue;
1411 }
1412 if (!info.isSpy()) {
1413 // The first touched non-spy window was found, so return the spy windows touched so far.
1414 return spyWindows;
1415 }
1416 spyWindows.push_back(windowHandle);
1417 }
1418 return spyWindows;
1419}
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 const char* reason;
1423 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001424 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001425 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001426 ALOGD("Dropped event because policy consumed it.");
1427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 reason = "inbound event was dropped because the policy consumed it";
1429 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001430 case DropReason::DISABLED:
1431 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 ALOGI("Dropped event because input dispatch is disabled.");
1433 }
1434 reason = "inbound event was dropped because input dispatch is disabled";
1435 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001436 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001437 LOG(INFO) << "Dropping because the current application is not responding and the user "
1438 "has started interacting with a different application: "
1439 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 reason = "inbound event was dropped because the current application is not responding "
1441 "and the user has started interacting with a different application";
1442 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001443 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 ALOGI("Dropped event because it is stale.");
1445 reason = "inbound event was dropped because it is stale";
1446 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001447 case DropReason::NO_POINTER_CAPTURE:
1448 ALOGI("Dropped event because there is no window with Pointer Capture.");
1449 reason = "inbound event was dropped because there is no window with Pointer Capture";
1450 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 case DropReason::NOT_DROPPED: {
1452 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 }
1456
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001458 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001459 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001460 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1461 options.displayId = keyEntry.displayId;
1462 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001466 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001467 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1468 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001469 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001470 options.displayId = motionEntry.displayId;
1471 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 synthesizeCancelationEventsForAllConnectionsLocked(options);
1473 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001474 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1475 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001476 options.displayId = motionEntry.displayId;
1477 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 synthesizeCancelationEventsForAllConnectionsLocked(options);
1479 }
1480 break;
1481 }
Chris Yef59a2f42020-10-16 12:55:26 -07001482 case EventEntry::Type::SENSOR: {
1483 break;
1484 }
arthurhungb89ccb02020-12-30 16:19:01 +08001485 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1486 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001487 break;
1488 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001489 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001490 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001491 case EventEntry::Type::CONFIGURATION_CHANGED:
1492 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001493 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001494 break;
1495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497}
1498
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001500 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501}
1502
Prabir Pradhancef936d2021-07-21 16:17:52 +00001503bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001504 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return false;
1506 }
1507
1508 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001509 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001510 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001511 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1512 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001513 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 return true;
1515}
1516
Prabir Pradhancef936d2021-07-21 16:17:52 +00001517void InputDispatcher::postCommandLocked(Command&& command) {
1518 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
1521void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001522 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001523 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001524 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 releaseInboundEventLocked(entry);
1526 }
1527 traceInboundQueueLengthLocked();
1528}
1529
1530void InputDispatcher::releasePendingEventLocked() {
1531 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001533 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535}
1536
Prabir Pradhan24047542023-11-02 17:14:59 +00001537void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001538 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001540 if (DEBUG_DISPATCH_CYCLE) {
1541 ALOGD("Injected inbound event was dropped.");
1542 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001543 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001546 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549}
1550
1551void InputDispatcher::resetKeyRepeatLocked() {
1552 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001553 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
1555}
1556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001557std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001558 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559
Michael Wright2e732952014-09-24 13:26:59 -07001560 uint32_t policyFlags = entry->policyFlags &
1561 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001564 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1565 currentTime, entry->deviceId, entry->source,
1566 entry->displayId, policyFlags, entry->action, entry->flags,
1567 entry->keyCode, entry->scanCode, entry->metaState,
1568 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001570 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001571 if (mTracer) {
1572 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1573 }
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578}
1579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
1586 // Reset key repeating in case a keyboard device was added or removed or something.
1587 resetKeyRepeatLocked();
1588
1589 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001590 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1591 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001592 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001593 };
1594 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 return true;
1596}
1597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001598bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1599 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1601 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1602 entry.deviceId);
1603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
liushenxiang42232912021-05-21 20:24:09 +08001605 // Reset key repeating in case a keyboard device was disabled or enabled.
1606 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1607 resetKeyRepeatLocked();
1608 }
1609
Michael Wrightfb04fd52022-11-24 22:31:11 +00001610 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001611 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001613
1614 // Remove all active pointers from this device
1615 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1616 touchState.removeAllPointersForDevice(entry.deviceId);
1617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 return true;
1619}
1620
Vishnu Nairad321cd2020-08-20 16:40:21 -07001621void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001622 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001623 if (mPendingEvent != nullptr) {
1624 // Move the pending event to the front of the queue. This will give the chance
1625 // for the pending event to get dispatched to the newly focused window
1626 mInboundQueue.push_front(mPendingEvent);
1627 mPendingEvent = nullptr;
1628 }
1629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001630 std::unique_ptr<FocusEntry> focusEntry =
1631 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1632 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001633
1634 // This event should go to the front of the queue, but behind all other focus events
1635 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001636 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1637 [](const std::shared_ptr<const EventEntry>& event) {
1638 return event->type == EventEntry::Type::FOCUS;
1639 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001640
1641 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001643}
1644
Prabir Pradhan24047542023-11-02 17:14:59 +00001645void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1646 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001647 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1648 if (connection == nullptr) {
1649 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001650 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001651 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001652 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001653 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001654 std::string reason = std::string("reason=").append(entry->reason);
1655 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001656 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001657}
1658
Prabir Pradhan99987712020-11-10 18:43:05 -08001659void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001660 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001661 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 dropReason = DropReason::NOT_DROPPED;
1663
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001666
1667 if (entry->pointerCaptureRequest.enable) {
1668 // Enable Pointer Capture.
1669 if (haveWindowWithPointerCapture &&
1670 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001671 // This can happen if pointer capture is disabled and re-enabled before we notify the
1672 // app of the state change, so there is no need to notify the app.
1673 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1674 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001675 }
1676 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001677 // This can happen if a window requests capture and immediately releases capture.
1678 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001679 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001680 return;
1681 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001682 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1683 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1684 return;
1685 }
1686
Vishnu Nairc519ff72021-01-21 08:23:08 -08001687 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001688 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1689 mWindowTokenWithPointerCapture = token;
1690 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001691 // Disable Pointer Capture.
1692 // We do not check if the sequence number matches for requests to disable Pointer Capture
1693 // for two reasons:
1694 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1695 // to disable capture with the same sequence number: one generated by
1696 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1697 // Capture being disabled in InputReader.
1698 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1699 // actual Pointer Capture state that affects events being generated by input devices is
1700 // in InputReader.
1701 if (!haveWindowWithPointerCapture) {
1702 // Pointer capture was already forcefully disabled because of focus change.
1703 dropReason = DropReason::NOT_DROPPED;
1704 return;
1705 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001706 token = mWindowTokenWithPointerCapture;
1707 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001708 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001709 setPointerCaptureLocked(false);
1710 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001711 }
1712
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001713 auto connection = getConnectionLocked(token);
1714 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001715 // Window has gone away, clean up Pointer Capture state.
1716 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001717 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001718 setPointerCaptureLocked(false);
1719 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001720 return;
1721 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001722 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001723 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001724
1725 dropReason = DropReason::NOT_DROPPED;
1726}
1727
Prabir Pradhan24047542023-11-02 17:14:59 +00001728void InputDispatcher::dispatchTouchModeChangeLocked(
1729 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001730 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001731 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001732 if (windowHandles.empty()) {
1733 return;
1734 }
1735 const std::vector<InputTarget> inputTargets =
1736 getInputTargetsFromWindowHandlesLocked(windowHandles);
1737 if (inputTargets.empty()) {
1738 return;
1739 }
1740 entry->dispatchInProgress = true;
1741 dispatchEventLocked(currentTime, entry, inputTargets);
1742}
1743
1744std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1745 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1746 std::vector<InputTarget> inputTargets;
1747 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001748 const sp<IBinder>& token = handle->getToken();
1749 if (token == nullptr) {
1750 continue;
1751 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001752 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1753 if (connection == nullptr) {
1754 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001755 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001756 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001757 }
1758 return inputTargets;
1759}
1760
Prabir Pradhan24047542023-11-02 17:14:59 +00001761bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001762 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001764 if (!entry->dispatchInProgress) {
1765 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1766 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1767 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1768 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001769 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 // We have seen two identical key downs in a row which indicates that the device
1771 // driver is automatically generating key repeats itself. We take note of the
1772 // repeat here, but we disable our own next key repeat timer since it is clear that
1773 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001774 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1775 // Make sure we don't get key down from a different device. If a different
1776 // device Id has same key pressed down, the new device Id will replace the
1777 // current one to hold the key repeat with repeat count reset.
1778 // In the future when got a KEY_UP on the device id, drop it and do not
1779 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1781 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001782 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 } else {
1784 // Not a repeat. Save key down state in case we do see a repeat later.
1785 resetKeyRepeatLocked();
1786 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1787 }
1788 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001789 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1790 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001791 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001792 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001793 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1794 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 resetKeyRepeatLocked();
1797 }
1798
1799 if (entry->repeatCount == 1) {
1800 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1801 } else {
1802 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1803 }
1804
1805 entry->dispatchInProgress = true;
1806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001807 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809
1810 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001811 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001813 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return false; // wait until next wakeup
1815 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001816 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 entry->interceptKeyWakeupTime = 0;
1818 }
1819
1820 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001821 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001823 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001824 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001825
1826 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1827 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1828 };
1829 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001830 // Poke user activity for keys not passed to user
1831 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 return false; // wait for the command to run
1833 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001834 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001836 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001837 if (*dropReason == DropReason::NOT_DROPPED) {
1838 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840 }
1841
1842 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001843 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001844 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1846 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001847 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001848 // Poke user activity for undispatched keys
1849 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return true;
1851 }
1852
1853 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 InputEventInjectionResult injectionResult;
1855 sp<WindowInfoHandle> focusedWindow =
1856 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1857 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return false;
1860 }
1861
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001862 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 return true;
1865 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001866 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1867
1868 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001869 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1870 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001872 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001873 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001875 if (mTracer) {
1876 ensureEventTraced(*entry);
1877 for (const auto& target : inputTargets) {
1878 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1879 }
1880 }
1881
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 // Dispatch the key.
1883 dispatchEventLocked(currentTime, entry, inputTargets);
1884 return true;
1885}
1886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001888 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1889 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1890 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1891 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1892 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1893 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1894 entry.metaState, entry.repeatCount, entry.downTime);
1895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896}
1897
Prabir Pradhancef936d2021-07-21 16:17:52 +00001898void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001899 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001900 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001901 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1902 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1903 "source=0x%x, sensorType=%s",
1904 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001905 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001907 auto command = [this, entry]() REQUIRES(mLock) {
1908 scoped_unlock unlock(mLock);
1909
1910 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001911 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001912 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001913 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1914 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001915 };
1916 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001917}
1918
1919bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001920 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1921 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001922 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001923 }
Chris Yef59a2f42020-10-16 12:55:26 -07001924 { // acquire lock
1925 std::scoped_lock _l(mLock);
1926
1927 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001928 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001929 if (entry->type == EventEntry::Type::SENSOR) {
1930 it = mInboundQueue.erase(it);
1931 releaseInboundEventLocked(entry);
1932 }
1933 }
1934 }
1935 return true;
1936}
1937
Prabir Pradhan24047542023-11-02 17:14:59 +00001938bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1939 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001940 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 entry->dispatchInProgress = true;
1945
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948
1949 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001950 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001951 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001952 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1953 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 return true;
1955 }
1956
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001957 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
1959 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001960 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 if (isPointerEvent) {
1964 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001965
1966 if (mDragState &&
1967 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1968 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1969 pilferPointersLocked(mDragState->dragWindow->getToken());
1970 }
1971
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001972 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001973 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001974 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1975 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 } else {
1977 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978 sp<WindowInfoHandle> focusedWindow =
1979 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1980 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1981 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001982 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1983 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1984 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 return false;
1989 }
1990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001991 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001992 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001993 return true;
1994 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001995 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001996 CancelationOptions::Mode mode(
1997 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1998 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001999 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002000 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002001 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 return true;
2003 }
2004
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002005 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002006 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002008 if (mTracer) {
2009 ensureEventTraced(*entry);
2010 for (const auto& target : inputTargets) {
2011 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2012 }
2013 }
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 dispatchEventLocked(currentTime, entry, inputTargets);
2017 return true;
2018}
2019
chaviw98318de2021-05-19 16:45:23 -05002020void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002021 bool isExiting, const int32_t rawX,
2022 const int32_t rawY) {
2023 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002024 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002025 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2026 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002027
2028 enqueueInboundEventLocked(std::move(dragEntry));
2029}
2030
Prabir Pradhan24047542023-11-02 17:14:59 +00002031void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2032 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002033 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2034 if (connection == nullptr) {
2035 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002036 }
arthurhungb89ccb02020-12-30 16:19:01 +08002037 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002038 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002039}
2040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002041void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002042 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002043 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002044 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002045 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002046 "metaState=0x%x, buttonState=0x%x,"
2047 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002048 prefix, entry.eventTime, entry.deviceId,
2049 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2050 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2051 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2052 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002054 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002055 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002056 "x=%f, y=%f, pressure=%f, size=%f, "
2057 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2058 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002059 i, entry.pointerProperties[i].id,
2060 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002061 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2062 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2063 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2064 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2065 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2066 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2067 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2068 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2069 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072}
2073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002074void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002075 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002078 if (DEBUG_DISPATCH_CYCLE) {
2079 ALOGD("dispatchEventToCurrentInputTargets");
2080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002082 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002083
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002088 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002089 std::shared_ptr<Connection> connection = inputTarget.connection;
2090 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092}
2093
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002094void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2096 // If the policy decides to close the app, we will get a channel removal event via
2097 // unregisterInputChannel, and will clean up the connection that way. We are already not
2098 // sending new pointers to the connection when it blocked, but focused events will continue to
2099 // pile up.
2100 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002101 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002102 if (connection->status != Connection::Status::NORMAL) {
2103 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002105 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2106 "application not responding");
2107
2108 sp<WindowInfoHandle> windowHandle;
2109 if (!connection->monitor) {
2110 windowHandle = getWindowHandleLocked(connection->getToken());
2111 if (windowHandle == nullptr) {
2112 // The window that is receiving this ANR was removed, so there is no need to generate
2113 // cancellations, because the cancellations would have already been generated when
2114 // the window was removed.
2115 return;
2116 }
2117 }
2118 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119}
2120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002122 if (DEBUG_FOCUS) {
2123 ALOGD("Resetting ANR timeouts.");
2124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002128 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129}
2130
Tiger Huang721e26f2018-07-24 22:26:19 +08002131/**
2132 * Get the display id that the given event should go to. If this event specifies a valid display id,
2133 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2134 * Focused display is the display that the user most recently interacted with.
2135 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002136int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002137 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002138 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002139 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002140 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2141 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 break;
2143 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002144 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2146 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 break;
2148 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002149 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002150 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002151 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002152 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002153 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002154 case EventEntry::Type::SENSOR:
2155 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002156 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 return ADISPLAY_ID_NONE;
2158 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002159 }
2160 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2161}
2162
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2164 const char* focusedWindowName) {
2165 if (mAnrTracker.empty()) {
2166 // already processed all events that we waited for
2167 mKeyIsWaitingForEventsTimeout = std::nullopt;
2168 return false;
2169 }
2170
2171 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2172 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002173 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002174 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002175 std::chrono::duration_cast<std::chrono::nanoseconds>(
2176 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002177 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 return true;
2179 }
2180
2181 // We still have pending events, and already started the timer
2182 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2183 return true; // Still waiting
2184 }
2185
2186 // Waited too long, and some connection still hasn't processed all motions
2187 // Just send the key to the focused window
2188 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2189 focusedWindowName);
2190 mKeyIsWaitingForEventsTimeout = std::nullopt;
2191 return false;
2192}
2193
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002194sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002195 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198
Tiger Huang721e26f2018-07-24 22:26:19 +08002199 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002200 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002201 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002202 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2203
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 // If there is no currently focused window and no focused application
2205 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2207 ALOGI("Dropping %s event because there is no focused window or focused application in "
2208 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002209 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002210 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
Vishnu Nair062a8672021-09-03 16:07:44 -07002213 // Drop key events if requested by input feature
2214 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002215 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002216 }
2217
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002218 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2219 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2220 // start interacting with another application via touch (app switch). This code can be removed
2221 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2222 // an app is expected to have a focused window.
2223 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2224 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2225 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002226 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2227 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2228 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002230 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231 ALOGW("Waiting because no window has focus but %s may eventually add a "
2232 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002233 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002234 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::PENDING;
2236 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2238 // Already raised ANR. Drop the event
2239 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002240 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002241 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 } else {
2243 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002244 outInjectionResult = InputEventInjectionResult::PENDING;
2245 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 }
2247 }
2248
2249 // we have a valid, non-null focused window
2250 resetNoFocusedWindowTimeoutLocked();
2251
Prabir Pradhan5735a322022-04-11 17:23:34 +00002252 // Verify targeted injection.
2253 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2254 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002255 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2256 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002259 if (focusedWindowHandle->getInfo()->inputConfig.test(
2260 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002261 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::PENDING;
2263 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 }
2265
2266 // If the event is a key event, then we must wait for all previous events to
2267 // complete before delivering it because previous events may have the
2268 // side-effect of transferring focus to a different window and we want to
2269 // ensure that the following keys are sent to the new window.
2270 //
2271 // Suppose the user touches a button in a window then immediately presses "A".
2272 // If the button causes a pop-up window to appear then we want to ensure that
2273 // the "A" key is delivered to the new pop-up window. This is because users
2274 // often anticipate pending UI changes when typing on a keyboard.
2275 // To obtain this behavior, we must serialize key events with respect to all
2276 // prior input events.
2277 if (entry.type == EventEntry::Type::KEY) {
2278 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002279 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002280 outInjectionResult = InputEventInjectionResult::PENDING;
2281 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002285 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2286 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287}
2288
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002289/**
2290 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2291 * that are currently unresponsive.
2292 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002293std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2294 const std::vector<Monitor>& monitors) const {
2295 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002296 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002297 [](const Monitor& monitor) REQUIRES(mLock) {
2298 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002299 if (!connection->responsive) {
2300 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002301 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002302 return false;
2303 }
2304 return true;
2305 });
2306 return responsiveMonitors;
2307}
2308
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002310 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002311 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002312 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002314 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 // For security reasons, we defer updating the touch state until we are sure that
2316 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 const int32_t displayId = entry.displayId;
2318 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002319 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320
2321 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002322 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 // Copy current touch state into tempTouchState.
2325 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2326 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002327 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002328 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2330 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002331 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002332 }
2333
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002334 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335
2336 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2337 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2338 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002339 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2340 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002341 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002342 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2343 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002344 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2345 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2346 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002347 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002348
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002349 if (newGesture) {
2350 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002351 }
2352
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002353 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2354 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2355 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002358 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002359 if (wasDown) {
2360 // Started hovering, but the device is already down: reject the hover event
2361 LOG(ERROR) << "Got hover event " << entry.getDescription()
2362 << " but the device is already down " << oldState->dump();
2363 outInjectionResult = InputEventInjectionResult::FAILED;
2364 return {};
2365 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002366 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2367 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002368 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002369 }
2370
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2372 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002373 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002374 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002375 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002376 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2377 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002378 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002379 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002380 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002381
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002382 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002383 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002386 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002387 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002390 }
2391
Prabir Pradhan5735a322022-04-11 17:23:34 +00002392 // Verify targeted injection.
2393 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2394 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002395 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002396 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002397 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002398 }
2399
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002401 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2403 // New window supports splitting, but we should never split mouse events.
2404 isSplit = !isFromMouse;
2405 } else if (isSplit) {
2406 // New window does not support splitting but we have already split events.
2407 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002408 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2409 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002410 newTouchedWindowHandle = nullptr;
2411 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 } else {
2413 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002414 // be delivered to a new window which supports split touch. Pointers from a mouse device
2415 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002416 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002417 }
2418
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002419 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002420 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002422 // Process the foreground window first so that it is the first to receive the event.
2423 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 }
2425
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002426 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002427 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2428 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002429 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002430 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002431 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002432 }
2433
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002435 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 continue;
2437 }
2438
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002439 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002440 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002441 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002442 }
2443
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002444 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002445 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002446
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002447 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2448 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002450 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002451
2452 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002453 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 }
2455 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002456 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002457 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002458 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002459 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002460
2461 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002462
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002463 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002464 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2465 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002466 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002467 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002468 isDownOrPointerDown
2469 ? std::make_optional(entry.eventTime)
2470 : std::nullopt);
2471 // If this is the pointer going down and the touched window has a wallpaper
2472 // then also add the touched wallpaper windows so they are locked in for the
2473 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2474 // SCROLL because the wallpaper engine only supports touch events. We would need to
2475 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2476 // handle these events.
2477 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002478 windowHandle->getInfo()->inputConfig.test(
2479 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2480 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2481 if (wallpaper != nullptr) {
2482 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2483 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002484 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002485 if (isSplit) {
2486 wallpaperFlags |= InputTarget::Flags::SPLIT;
2487 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002488 tempTouchState.addOrUpdateWindow(wallpaper,
2489 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002490 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002491 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002492 }
2493 }
2494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002496
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002497 // If a window is already pilfering some pointers, give it this new pointer as well and
2498 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2499 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002500 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002501 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002502 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002503 // This window is already pilfering some pointers, and this new pointer is also
2504 // going to it. Therefore, take over this pointer and don't give it to anyone
2505 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002506 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002507 }
2508 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002509
2510 // Restrict all pilfered pointers to the pilfering windows.
2511 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 } else {
2513 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2514
2515 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002516 if (!tempTouchState.isDown(entry.deviceId) &&
2517 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002518 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2519 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2520 << " is not down or we previously dropped the pointer down event in "
2521 << "display " << displayId << ": " << entry.getDescription();
2522 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002523 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002524 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002527 // If the pointer is not currently hovering, then ignore the event.
2528 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2529 const int32_t pointerId = entry.pointerProperties[0].id;
2530 if (oldState == nullptr ||
2531 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2532 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2533 "display "
2534 << displayId << ": " << entry.getDescription();
2535 outInjectionResult = InputEventInjectionResult::FAILED;
2536 return {};
2537 }
2538 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2539 }
2540
arthurhung6d4bed92021-03-17 11:59:33 +08002541 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002542
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002544 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002545 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002546 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002547 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002548 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002549 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002550 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002551 sp<WindowInfoHandle> newTouchedWindowHandle =
2552 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002553
Prabir Pradhan5735a322022-04-11 17:23:34 +00002554 // Verify targeted injection.
2555 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2556 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002557 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002558 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002559 }
2560
Linnan Libf069a32024-02-29 17:22:59 +00002561 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002562 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002563 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002564 newTouchedWindowHandle = nullptr;
2565 }
2566
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002567 if (newTouchedWindowHandle != nullptr &&
2568 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002569 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002570 oldTouchedWindowHandle->getName().c_str(),
2571 newTouchedWindowHandle->getName().c_str(), displayId);
2572
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002574 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002575 const PointerProperties& pointer = entry.pointerProperties[0];
2576 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002577
2578 const TouchedWindow& touchedWindow =
2579 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002580 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002581 InputTarget::DispatchMode::SLIPPERY_EXIT,
2582 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002583 touchedWindow.getDownTimeInTarget(entry.deviceId),
2584 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585
2586 // Make a slippery entrance into the new window.
2587 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002588 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002591 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002592 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002593 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002596 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002599 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002600 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002601 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002604 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2605 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002606 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002607 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002608
2609 // Check if the wallpaper window should deliver the corresponding event.
2610 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002611 tempTouchState, entry.deviceId, pointer, targets);
2612 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002613 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615 }
Arthur Hung96483742022-11-15 03:30:48 +00002616
2617 // Update the pointerIds for non-splittable when it received pointer down.
2618 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2619 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002620 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002621 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2622 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002623 // Ignore drag window for it should just track one pointer.
2624 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2625 continue;
2626 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002627 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002628 }
2629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 }
2631
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002632 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002633 {
2634 std::vector<TouchedWindow> hoveringWindows =
2635 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2636 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002637 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002638 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2639 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002640 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002641 if (!target) {
2642 continue;
2643 }
2644 // Hardcode to single hovering pointer for now.
2645 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2646 pointerIds.set(entry.pointerProperties[0].id);
2647 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2648 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651
Prabir Pradhan5735a322022-04-11 17:23:34 +00002652 // Ensure that all touched windows are valid for injection.
2653 if (entry.injectionState != nullptr) {
2654 std::string errs;
2655 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002656 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2657 if (err) errs += "\n - " + *err;
2658 }
2659 if (!errs.empty()) {
2660 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002661 "%s:%s",
2662 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002663 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002664 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002665 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002667
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002668 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2669 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002671 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002672 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002673 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002674 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002675 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002676 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002677 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002678 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002679 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2680 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683 }
2684 }
2685 }
2686
Harry Cuttsb166c002023-05-09 13:06:05 +00002687 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2688 // only want the system UI to handle these gestures.
2689 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2690 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2691 if (isTouchpadNavGesture) {
2692 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2693 }
2694
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002695 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002696 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002697 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002698 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002699 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002700 continue;
2701 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002702 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002703 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002704 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002705 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002706
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002707 // During targeted injection, only allow owned targets to receive events
2708 std::erase_if(targets, [&](const InputTarget& target) {
2709 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2710 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2711 if (err) {
2712 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2713 << ": " << (*err);
2714 return true;
2715 }
2716 return false;
2717 });
2718
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002719 if (targets.empty()) {
2720 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2721 outInjectionResult = InputEventInjectionResult::FAILED;
2722 return {};
2723 }
2724
2725 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2726 // window that is actually receiving the entire gesture.
2727 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002728 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002729 })) {
2730 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2731 << entry.getDescription();
2732 outInjectionResult = InputEventInjectionResult::FAILED;
2733 return {};
2734 }
2735
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002736 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
Prabir Pradhan502a7252023-12-01 16:11:24 +00002738 // Now that we have generated all of the input targets for this event, reset the dispatch
2739 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002740 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002741 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002742 }
2743
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002744 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002745 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002746 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002747 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002748 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002749 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002750 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002751 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2752 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002753 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2754 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2755 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002758 // Save changes unless the action was scroll in which case the temporary touch
2759 // state was only valid for this one action.
2760 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002761 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002762 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002763 mTouchStatesByDisplay[displayId] = tempTouchState;
2764 } else {
2765 mTouchStatesByDisplay.erase(displayId);
2766 }
2767 }
2768
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002769 if (tempTouchState.windows.empty()) {
2770 mTouchStatesByDisplay.erase(displayId);
2771 }
2772
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002773 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774}
2775
arthurhung6d4bed92021-03-17 11:59:33 +08002776void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002777 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2778 // have an explicit reason to support it.
2779 constexpr bool isStylus = false;
2780
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002781 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002782 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002783 if (dropWindow) {
2784 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002785 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002786 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002787 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002788 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002789 }
2790 mDragState.reset();
2791}
2792
2793void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002794 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002795 return;
2796 }
2797
arthurhung6d4bed92021-03-17 11:59:33 +08002798 if (!mDragState->isStartDrag) {
2799 mDragState->isStartDrag = true;
2800 mDragState->isStylusButtonDownAtStart =
2801 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2802 }
2803
Arthur Hung54745652022-04-20 07:17:41 +00002804 // Find the pointer index by id.
2805 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002806 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002807 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2808 if (pointerProperties.id == mDragState->pointerId) {
2809 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002810 }
Arthur Hung54745652022-04-20 07:17:41 +00002811 }
arthurhung6d4bed92021-03-17 11:59:33 +08002812
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002813 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002814 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002815 }
2816
2817 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2818 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2819 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2820
2821 switch (maskedAction) {
2822 case AMOTION_EVENT_ACTION_MOVE: {
2823 // Handle the special case : stylus button no longer pressed.
2824 bool isStylusButtonDown =
2825 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2826 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2827 finishDragAndDrop(entry.displayId, x, y);
2828 return;
2829 }
2830
2831 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2832 // until we have an explicit reason to support it.
2833 constexpr bool isStylus = false;
2834
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002835 sp<WindowInfoHandle> hoverWindowHandle =
2836 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2837 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002838 // enqueue drag exit if needed.
2839 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2840 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2841 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002842 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002843 y);
2844 }
2845 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2846 }
2847 // enqueue drag location if needed.
2848 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002849 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002850 }
2851 break;
2852 }
2853
2854 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002855 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002856 break;
2857 }
2858 // The drag pointer is up.
2859 [[fallthrough]];
2860 case AMOTION_EVENT_ACTION_UP:
2861 finishDragAndDrop(entry.displayId, x, y);
2862 break;
2863 case AMOTION_EVENT_ACTION_CANCEL: {
2864 ALOGD("Receiving cancel when drag and drop.");
2865 sendDropWindowCommandLocked(nullptr, 0, 0);
2866 mDragState.reset();
2867 break;
2868 }
arthurhungb89ccb02020-12-30 16:19:01 +08002869 }
2870}
2871
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2873 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002874 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002875 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002876 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2877 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002878 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2879 return {};
2880 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002881 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002882 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002883 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002884 inputTarget.flags = targetFlags;
2885 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2886 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2887 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2888 if (displayInfoIt != mDisplayInfos.end()) {
2889 inputTarget.displayTransform = displayInfoIt->second.transform;
2890 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002891 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002892 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2893 }
2894 return inputTarget;
2895}
2896
chaviw98318de2021-05-19 16:45:23 -05002897void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002898 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002899 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002900 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002901 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002902 std::vector<InputTarget>::iterator it =
2903 std::find_if(inputTargets.begin(), inputTargets.end(),
2904 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002905 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002906 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002907
chaviw98318de2021-05-19 16:45:23 -05002908 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002909
2910 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002911 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002912 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2913 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002914 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002915 return;
2916 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002917 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002918 it = inputTargets.end() - 1;
2919 }
2920
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002921 if (it->flags != targetFlags) {
2922 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2923 }
2924 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2925 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2926 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2927 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002928}
2929
2930void InputDispatcher::addPointerWindowTargetLocked(
2931 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002932 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2933 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2934 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002935 if (pointerIds.none()) {
2936 for (const auto& target : inputTargets) {
2937 LOG(INFO) << "Target: " << target;
2938 }
2939 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2940 return;
2941 }
2942 std::vector<InputTarget>::iterator it =
2943 std::find_if(inputTargets.begin(), inputTargets.end(),
2944 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002945 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002946 });
2947
2948 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2949 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2950 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2951 // input targets for hovering pointers and for touching pointers.
2952 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2953 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002954 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002955 // Force the code below to create a new input target
2956 it = inputTargets.end();
2957 }
2958
2959 const WindowInfo* windowInfo = windowHandle->getInfo();
2960
2961 if (it == inputTargets.end()) {
2962 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002963 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2964 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002965 if (!target) {
2966 return;
2967 }
2968 inputTargets.push_back(*target);
2969 it = inputTargets.end() - 1;
2970 }
2971
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002972 if (it->dispatchMode != dispatchMode) {
2973 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2974 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2975 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002976 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002977 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2978 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002979 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002980 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002981 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002982 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2983 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002984
chaviw1ff3d1e2020-07-01 15:53:47 -07002985 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986}
2987
Michael Wright3dd60e22019-03-27 22:06:44 +00002988void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002989 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002990 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2991 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002992
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002993 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002994 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002995 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2996 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002997 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2998 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002999 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003000 target.setDefaultPointerTransform(target.displayTransform);
3001 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 }
3003}
3004
Robert Carrc9bf1d32020-04-13 17:21:08 -07003005/**
3006 * Indicate whether one window handle should be considered as obscuring
3007 * another window handle. We only check a few preconditions. Actually
3008 * checking the bounds is left to the caller.
3009 */
chaviw98318de2021-05-19 16:45:23 -05003010static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3011 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003012 // Compare by token so cloned layers aren't counted
3013 if (haveSameToken(windowHandle, otherHandle)) {
3014 return false;
3015 }
3016 auto info = windowHandle->getInfo();
3017 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003018 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003019 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003020 } else if (otherInfo->alpha == 0 &&
3021 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003022 // Those act as if they were invisible, so we don't need to flag them.
3023 // We do want to potentially flag touchable windows even if they have 0
3024 // opacity, since they can consume touches and alter the effects of the
3025 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003026 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003027 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3028 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003029 } else if (info->ownerUid == otherInfo->ownerUid) {
3030 // If ownerUid is the same we don't generate occlusion events as there
3031 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003032 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003033 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003034 return false;
3035 } else if (otherInfo->displayId != info->displayId) {
3036 return false;
3037 }
3038 return true;
3039}
3040
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003041/**
3042 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3043 * untrusted, one should check:
3044 *
3045 * 1. If result.hasBlockingOcclusion is true.
3046 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3047 * BLOCK_UNTRUSTED.
3048 *
3049 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3050 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3051 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3052 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3053 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3054 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3055 *
3056 * If neither of those is true, then it means the touch can be allowed.
3057 */
3058InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003059 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3060 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003061 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003062 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 TouchOcclusionInfo info;
3064 info.hasBlockingOcclusion = false;
3065 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003066 info.obscuringUid = gui::Uid::INVALID;
3067 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003068 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003069 if (windowHandle == otherHandle) {
3070 break; // All future windows are below us. Exit early.
3071 }
chaviw98318de2021-05-19 16:45:23 -05003072 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003073 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3074 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003075 if (DEBUG_TOUCH_OCCLUSION) {
3076 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003077 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003078 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003079 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3080 // we perform the checks below to see if the touch can be propagated or not based on the
3081 // window's touch occlusion mode
3082 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3083 info.hasBlockingOcclusion = true;
3084 info.obscuringUid = otherInfo->ownerUid;
3085 info.obscuringPackage = otherInfo->packageName;
3086 break;
3087 }
3088 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003089 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003090 float opacity =
3091 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3092 // Given windows A and B:
3093 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3094 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3095 opacityByUid[uid] = opacity;
3096 if (opacity > info.obscuringOpacity) {
3097 info.obscuringOpacity = opacity;
3098 info.obscuringUid = uid;
3099 info.obscuringPackage = otherInfo->packageName;
3100 }
3101 }
3102 }
3103 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003104 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003105 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003106 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003107 return info;
3108}
3109
chaviw98318de2021-05-19 16:45:23 -05003110std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003111 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003112 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003113 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3114 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3115 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003116 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003117 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003118 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3119 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003120 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3121 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3122 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003123 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003124}
3125
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003126bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3127 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003128 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3129 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003130 return false;
3131 }
3132 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003133 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003134 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003135 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003136 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3137 return false;
3138 }
3139 return true;
3140}
3141
chaviw98318de2021-05-19 16:45:23 -05003142bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003145 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3146 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003147 if (windowHandle == otherHandle) {
3148 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 }
chaviw98318de2021-05-19 16:45:23 -05003150 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003151 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003152 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 return true;
3154 }
3155 }
3156 return false;
3157}
3158
chaviw98318de2021-05-19 16:45:23 -05003159bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003160 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003161 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3162 const WindowInfo* windowInfo = windowHandle->getInfo();
3163 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003164 if (windowHandle == otherHandle) {
3165 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003166 }
chaviw98318de2021-05-19 16:45:23 -05003167 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003168 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003169 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003170 return true;
3171 }
3172 }
3173 return false;
3174}
3175
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003176std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003177 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003178 if (applicationHandle != nullptr) {
3179 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003180 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 } else {
3182 return applicationHandle->getName();
3183 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003184 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003185 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
3189}
3190
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003191void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003192 if (!isUserActivityEvent(eventEntry)) {
3193 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003194 return;
3195 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003196
3197 const int32_t eventType = getUserActivityEventType(eventEntry);
3198 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3199 // Note that we're directly getting the time diff between the current event and the previous
3200 // event. This is assuming that the first user event always happens at a timestamp that is
3201 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3202 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3203 // value than the potential first user activity event time, so this is ok.
3204 std::chrono::nanoseconds timeSinceLastEvent =
3205 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3206 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3207 return;
3208 }
3209 }
3210
Tiger Huang721e26f2018-07-24 22:26:19 +08003211 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003212 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003213 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003214 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003215 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003216 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003217 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
3219 }
3220
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003221 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003222 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3224 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 return;
3226 }
Josep del Riob3981622023-04-18 15:49:45 +00003227 if (windowDisablingUserActivityInfo != nullptr) {
3228 if (DEBUG_DISPATCH_CYCLE) {
3229 ALOGD("Not poking user activity: disabled by window '%s'.",
3230 windowDisablingUserActivityInfo->name.c_str());
3231 }
3232 return;
3233 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003236 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003237 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3238 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 return;
3240 }
Josep del Riob3981622023-04-18 15:49:45 +00003241 // If the key code is unknown, we don't consider it user activity
3242 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3243 return;
3244 }
3245 // Don't inhibit events that were intercepted or are not passed to
3246 // the apps, like system shortcuts
3247 if (windowDisablingUserActivityInfo != nullptr &&
3248 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3249 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3250 if (DEBUG_DISPATCH_CYCLE) {
3251 ALOGD("Not poking user activity: disabled by window '%s'.",
3252 windowDisablingUserActivityInfo->name.c_str());
3253 }
3254 return;
3255 }
3256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003259 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003260 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003261 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003262 break;
3263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 }
3265
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003266 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003267 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3268 REQUIRES(mLock) {
3269 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003270 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003271 };
3272 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273}
3274
3275void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003276 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003277 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003278 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003279 ATRACE_NAME_IF(ATRACE_ENABLED(),
3280 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3281 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003282 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003283 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003284 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003286 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003287 inputTarget.getPointerInfoString().c_str());
3288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
3290 // Skip this event if the connection status is not normal.
3291 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003292 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003293 if (DEBUG_DISPATCH_CYCLE) {
3294 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003295 connection->getInputChannelName().c_str(),
3296 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 return;
3299 }
3300
3301 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003302 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003303 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003304 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003305 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003307 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003308 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003309 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3310 logDispatchStateLocked();
3311 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3312 "target on connection "
3313 << connection->getInputChannelName() << " for "
3314 << originalMotionEntry.getDescription();
3315 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003317 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003318 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 if (!splitMotionEntry) {
3320 return; // split event was dropped
3321 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003322 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3323 std::string reason = std::string("reason=pointer cancel on split window");
3324 android_log_event_list(LOGTAG_INPUT_CANCEL)
3325 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3326 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003327 if (DEBUG_FOCUS) {
3328 ALOGD("channel '%s' ~ Split motion event.",
3329 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003330 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003331 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003332 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3333 std::move(splitMotionEntry),
3334 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 return;
3336 }
3337 }
3338
3339 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003340 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3341 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342}
3343
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003344void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3345 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3346 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003347 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003348 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3349 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003350 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003351
hongzuo liu95785e22022-09-06 02:51:35 +00003352 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003354 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
3356 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003357 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 startDispatchCycleLocked(currentTime, connection);
3359 }
3360}
3361
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003362void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003363 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003364 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003365 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3366 eventEntry->type == EventEntry::Type::MOTION;
3367 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3368 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3369 << inputTarget << " connection: " << connection->getInputChannelName()
3370 << " entry: " << eventEntry->getDescription();
3371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 // This is a new event.
3373 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003374 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003375 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3376 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003378 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3379 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003380 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003382 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003383 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003384 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3385 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003386 LOG(WARNING) << "channel " << connection->getInputChannelName()
3387 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003388 return; // skip the inconsistent event
3389 }
3390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003393 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003394 std::shared_ptr<const MotionEntry> resolvedMotion =
3395 std::static_pointer_cast<const MotionEntry>(eventEntry);
3396 {
3397 // Determine the resolved motion entry.
3398 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3399 int32_t resolvedAction = motionEntry.action;
3400 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003402 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003403 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003404 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003405 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003406 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003407 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003408 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003409 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003410 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003411 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3412 }
3413 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3414 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3415 motionEntry.displayId)) {
3416 if (DEBUG_DISPATCH_CYCLE) {
3417 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3418 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3419 "enter event";
3420 }
3421 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3422 }
3423
3424 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3425 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3426 }
3427 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3428 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3429 }
3430 if (dispatchEntry->targetFlags.test(
3431 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3432 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3433 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003434 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3435 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3436 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003437
3438 dispatchEntry->resolvedFlags = resolvedFlags;
3439 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003440 std::optional<std::vector<PointerProperties>> usingProperties;
3441 std::optional<std::vector<PointerCoords>> usingCoords;
3442 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3443 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3444 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3445 // the dispatcher, and therefore the coordinates of this event are currently
3446 // incorrect. These events should use the coordinates of the last dispatched
3447 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3448 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3449 std::optional<std::pair<std::vector<PointerProperties>,
3450 std::vector<PointerCoords>>>
3451 pointerInfo =
3452 connection->inputState.getPointersOfLastEvent(motionEntry,
3453 hovering);
3454 if (pointerInfo) {
3455 usingProperties = pointerInfo->first;
3456 usingCoords = pointerInfo->second;
3457 }
3458 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003459 // Generate a new MotionEntry with a new eventId using the resolved action and
3460 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003461 resolvedMotion = std::make_shared<
3462 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3463 motionEntry.eventTime, motionEntry.deviceId,
3464 motionEntry.source, motionEntry.displayId,
3465 motionEntry.policyFlags, resolvedAction,
3466 motionEntry.actionButton, resolvedFlags,
3467 motionEntry.metaState, motionEntry.buttonState,
3468 motionEntry.classification, motionEntry.edgeFlags,
3469 motionEntry.xPrecision, motionEntry.yPrecision,
3470 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3471 motionEntry.downTime,
3472 usingProperties.value_or(motionEntry.pointerProperties),
3473 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003474 if (ATRACE_ENABLED()) {
3475 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3476 ") to MotionEvent(id=0x%" PRIx32 ").",
3477 motionEntry.id, resolvedMotion->id);
3478 ATRACE_NAME(message.c_str());
3479 }
3480
3481 // Set the resolved motion entry in the DispatchEntry.
3482 dispatchEntry->eventEntry = resolvedMotion;
3483 eventEntry = resolvedMotion;
3484 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003487 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3488 // devices being active at the same time in the same window, so if a new device is
3489 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003490 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003491 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003492 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003493 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003494 << connection->getInputChannelName() << " with event "
3495 << cancelEvent->getDescription();
3496 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003497 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003498 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003499
3500 // Send these cancel events to the queue before sending the event from the new
3501 // device.
3502 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3503 }
3504
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003505 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003506 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003507 LOG(WARNING) << "channel " << connection->getInputChannelName()
3508 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003509 return; // skip the inconsistent event
3510 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003511 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003512 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003513 // Skip reporting pointer down outside focus to the policy.
3514 break;
3515 }
3516
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003517 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003518 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519
3520 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003522 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003523 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003524 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3525 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003526 break;
3527 }
Chris Yef59a2f42020-10-16 12:55:26 -07003528 case EventEntry::Type::SENSOR: {
3529 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3530 break;
3531 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003532 case EventEntry::Type::CONFIGURATION_CHANGED:
3533 case EventEntry::Type::DEVICE_RESET: {
3534 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003535 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003536 break;
3537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539
3540 // Remember that we are waiting for this dispatch to complete.
3541 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003542 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
3545 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003546 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003547 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003548}
3549
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003550/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003551 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003552 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003553 * The first role is to log input interaction with windows, which helps determine what the user was
3554 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3555 * that user started interacting with launcher window, as well as any other window that received
3556 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3557 * when the set of tokens that received the event changes. It is not logged again as long as the
3558 * user is interacting with the same windows.
3559 *
3560 * The second role is to track input device activity for metrics collection. For each input event,
3561 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3562 * input_interaction logs, the device interaction is reported even when the set of interaction
3563 * tokens do not change.
3564 *
3565 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3566 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003567 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003568void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3569 const std::vector<InputTarget>& targets) {
3570 int32_t deviceId;
3571 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003572 // Skip ACTION_UP events, and all events other than keys and motions
3573 if (entry.type == EventEntry::Type::KEY) {
3574 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3575 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3576 return;
3577 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003578 deviceId = keyEntry.deviceId;
3579 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 } else if (entry.type == EventEntry::Type::MOTION) {
3581 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3582 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003583 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3584 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003585 return;
3586 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003587 deviceId = motionEntry.deviceId;
3588 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003589 } else {
3590 return; // Not a key or a motion
3591 }
3592
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003593 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003594 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003595 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003596 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003597 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003598 continue; // Skip windows that receive ACTION_OUTSIDE
3599 }
3600
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003601 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003602 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003603 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003604 if (target.windowHandle) {
3605 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3606 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003607 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003608
3609 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3610 REQUIRES(mLock) {
3611 scoped_unlock unlock(mLock);
3612 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3613 };
3614 postCommandLocked(std::move(command));
3615
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003616 if (newConnectionTokens == mInteractionConnectionTokens) {
3617 return; // no change
3618 }
3619 mInteractionConnectionTokens = newConnectionTokens;
3620
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003621 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003622 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003623 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003624 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003625 std::string message = "Interaction with: " + targetList;
3626 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003627 message += "<none>";
3628 }
3629 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3630}
3631
chaviwfd6d3512019-03-25 13:23:49 -07003632void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003633 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003634 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003635 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3636 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003637 return;
3638 }
3639
Vishnu Nairc519ff72021-01-21 08:23:08 -08003640 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003641 if (focusedToken == token) {
3642 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003643 return;
3644 }
3645
Prabir Pradhancef936d2021-07-21 16:17:52 +00003646 auto command = [this, token]() REQUIRES(mLock) {
3647 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003648 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003649 };
3650 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651}
3652
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003653status_t InputDispatcher::publishMotionEvent(Connection& connection,
3654 DispatchEntry& dispatchEntry) const {
3655 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3656 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3657
3658 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003659 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003660
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003661 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003662 // Set the X and Y offset and X and Y scale depending on the input source.
3663 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003664 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3666 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003667 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003668 scaledCoords[i] = motionEntry.pointerCoords[i];
3669 // Don't apply window scale here since we don't want scale to affect raw
3670 // coordinates. The scale will be sent back to the client and applied
3671 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003672 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003673 }
3674 usingCoords = scaledCoords;
3675 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003676 }
3677
3678 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3679
3680 // Publish the motion event.
3681 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003682 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3683 motionEntry.source, motionEntry.displayId, std::move(hmac),
3684 motionEntry.action, motionEntry.actionButton,
3685 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3686 motionEntry.metaState, motionEntry.buttonState,
3687 motionEntry.classification, dispatchEntry.transform,
3688 motionEntry.xPrecision, motionEntry.yPrecision,
3689 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3690 dispatchEntry.rawTransform, motionEntry.downTime,
3691 motionEntry.eventTime, motionEntry.getPointerCount(),
3692 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003693}
3694
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003696 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003697 ATRACE_NAME_IF(ATRACE_ENABLED(),
3698 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3699 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003700 if (DEBUG_DISPATCH_CYCLE) {
3701 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003704 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003705 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003707 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003708 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
3710 // Publish the event.
3711 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003712 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3713 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003714 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3716 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003717 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003718 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3719 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003723 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003724 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3725 keyEntry.deviceId, keyEntry.source,
3726 keyEntry.displayId, std::move(hmac),
3727 keyEntry.action, dispatchEntry->resolvedFlags,
3728 keyEntry.keyCode, keyEntry.scanCode,
3729 keyEntry.metaState, keyEntry.repeatCount,
3730 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003731 if (mTracer) {
3732 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3733 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003734 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003737 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003738 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003739 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3740 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003741 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003742 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003743 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003744 if (mTracer) {
3745 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 break;
3748 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003749
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003750 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003751 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003752 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003753 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003754 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003755 break;
3756 }
3757
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003758 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3759 const TouchModeEntry& touchModeEntry =
3760 static_cast<const TouchModeEntry&>(eventEntry);
3761 status = connection->inputPublisher
3762 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3763 touchModeEntry.inTouchMode);
3764
3765 break;
3766 }
3767
Prabir Pradhan99987712020-11-10 18:43:05 -08003768 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3769 const auto& captureEntry =
3770 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3771 status = connection->inputPublisher
3772 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003773 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003774 break;
3775 }
3776
arthurhungb89ccb02020-12-30 16:19:01 +08003777 case EventEntry::Type::DRAG: {
3778 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3779 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3780 dragEntry.id, dragEntry.x,
3781 dragEntry.y,
3782 dragEntry.isExiting);
3783 break;
3784 }
3785
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003786 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003787 case EventEntry::Type::DEVICE_RESET:
3788 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003789 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003790 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794
3795 // Check the result.
3796 if (status) {
3797 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003798 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 "This is unexpected because the wait queue is empty, so the pipe "
3801 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003802 "event to it, status=%s(%d)",
3803 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3804 status);
Harry Cutts33476232023-01-30 19:57:29 +00003805 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 } else {
3807 // Pipe is full and we are waiting for the app to finish process some events
3808 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003809 if (DEBUG_DISPATCH_CYCLE) {
3810 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3811 "waiting for the application to catch up",
3812 connection->getInputChannelName().c_str());
3813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
3815 } else {
3816 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003817 "status=%s(%d)",
3818 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3819 status);
Harry Cutts33476232023-01-30 19:57:29 +00003820 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822 return;
3823 }
3824
3825 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003826 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3827 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3828 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003829 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003830 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003831 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003832 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003833 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835}
3836
chaviw09c8d2d2020-08-24 15:48:26 -07003837std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3838 size_t size;
3839 switch (event.type) {
3840 case VerifiedInputEvent::Type::KEY: {
3841 size = sizeof(VerifiedKeyEvent);
3842 break;
3843 }
3844 case VerifiedInputEvent::Type::MOTION: {
3845 size = sizeof(VerifiedMotionEvent);
3846 break;
3847 }
3848 }
3849 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3850 return mHmacKeyManager.sign(start, size);
3851}
3852
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003853const std::array<uint8_t, 32> InputDispatcher::getSignature(
3854 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003855 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003856 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003857 // Only sign events up and down events as the purely move events
3858 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003859 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003860 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003861
3862 VerifiedMotionEvent verifiedEvent =
3863 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3864 verifiedEvent.actionMasked = actionMasked;
3865 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3866 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003867}
3868
3869const std::array<uint8_t, 32> InputDispatcher::getSignature(
3870 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3871 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3872 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003873 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003874}
3875
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003877 const std::shared_ptr<Connection>& connection,
3878 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003879 if (DEBUG_DISPATCH_CYCLE) {
3880 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3881 connection->getInputChannelName().c_str(), seq, toString(handled));
3882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003884 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 return;
3886 }
3887
3888 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003889 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3890 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3891 };
3892 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893}
3894
3895void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003896 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003897 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003898 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003899 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3900 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
3903 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003904 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003905 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003906 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003907 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
3909 // The connection appears to be unrecoverably broken.
3910 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003911 if (connection->status == Connection::Status::NORMAL) {
3912 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 if (notify) {
3915 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003916 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3917 connection->getInputChannelName().c_str());
3918
3919 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003920 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003921 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003922 };
3923 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 }
3925 }
3926}
3927
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003928void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003929 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003930 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003931 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 }
3933}
3934
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003935void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003937 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939}
3940
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003941int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3942 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003943 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003944 if (connection == nullptr) {
3945 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3946 connectionToken.get(), events);
3947 return 0; // remove the callback
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003950 bool notify;
3951 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3952 if (!(events & ALOOPER_EVENT_INPUT)) {
3953 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3954 "events=0x%x",
3955 connection->getInputChannelName().c_str(), events);
3956 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 }
3958
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003959 nsecs_t currentTime = now();
3960 bool gotOne = false;
3961 status_t status = OK;
3962 for (;;) {
3963 Result<InputPublisher::ConsumerResponse> result =
3964 connection->inputPublisher.receiveConsumerResponse();
3965 if (!result.ok()) {
3966 status = result.error().code();
3967 break;
3968 }
3969
3970 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3971 const InputPublisher::Finished& finish =
3972 std::get<InputPublisher::Finished>(*result);
3973 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3974 finish.consumeTime);
3975 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003976 if (shouldReportMetricsForConnection(*connection)) {
3977 const InputPublisher::Timeline& timeline =
3978 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003979 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3980 connection->getToken(),
3981 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003982 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003983 }
3984 gotOne = true;
3985 }
3986 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003987 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003988 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 return 1;
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
3992
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003993 notify = status != DEAD_OBJECT || !connection->monitor;
3994 if (notify) {
3995 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3996 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3997 status);
3998 }
3999 } else {
4000 // Monitor channels are never explicitly unregistered.
4001 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004002 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004003 notify = !connection->monitor && stillHaveWindowHandle;
4004 if (notify) {
4005 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4006 connection->getInputChannelName().c_str(), events);
4007 }
4008 }
4009
4010 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004011 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004012 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013}
4014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004017 // Cancel windows (i.e. non-monitors).
4018 // A channel must have at least one window to receive any input. If a window was removed, the
4019 // event streams directed to the window will already have been canceled during window removal.
4020 // So there is no need to generate cancellations for connections without any windows.
4021 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4022 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4023 // through a non-touched window if there are more than one window for an input channel.
4024 if (cancelPointers) {
4025 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4026 if (options.displayId.has_value() && options.displayId != displayId) {
4027 continue;
4028 }
4029 for (const auto& touchedWindow : touchState.windows) {
4030 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4031 }
4032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004034 // Follow up by generating cancellations for all windows, because we don't explicitly track
4035 // the windows that have an ongoing focus event stream.
4036 if (cancelNonPointers) {
4037 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4038 for (const auto& windowHandle : handles) {
4039 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4040 }
4041 }
4042 }
4043
4044 // Cancel monitors.
4045 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046}
4047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004049 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004050 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004051 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004052 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4053 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004054 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004055 }
4056}
4057
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004058void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4059 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4060 const std::shared_ptr<Connection>& connection) {
4061 if (windowHandle == nullptr) {
4062 LOG(FATAL) << __func__ << ": Window handle must not be null";
4063 }
4064 if (connection) {
4065 // The connection can be optionally provided to avoid multiple lookups.
4066 if (windowHandle->getToken() != connection->getToken()) {
4067 LOG(FATAL) << __func__
4068 << ": Wrong connection provided for window: " << windowHandle->getName();
4069 }
4070 }
4071
4072 std::shared_ptr<Connection> resolvedConnection =
4073 connection ? connection : getConnectionLocked(windowHandle->getToken());
4074 if (!resolvedConnection) {
4075 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4076 return;
4077 }
4078 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4079}
4080
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004082 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4083 const sp<WindowInfoHandle>& window) {
4084 if (!connection->monitor && window == nullptr) {
4085 LOG(FATAL) << __func__
4086 << ": Cannot send event to non-monitor channel without a window - channel: "
4087 << connection->getInputChannelName();
4088 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004089 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 return;
4091 }
4092
4093 nsecs_t currentTime = now();
4094
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004095 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004096 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004098 if (cancelationEvents.empty()) {
4099 return;
4100 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004101
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004102 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4103 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004104 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004105 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004106 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004107 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004108
Arthur Hungb3307ee2021-10-14 10:57:37 +00004109 std::string reason = std::string("reason=").append(options.reason);
4110 android_log_event_list(LOGTAG_INPUT_CANCEL)
4111 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4112
hongzuo liu95785e22022-09-06 02:51:35 +00004113 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004114 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004115 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004116 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004117
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004118 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004119 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004120 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004121
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004122 switch (cancelationEventEntry->type) {
4123 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004124 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004125 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004126 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4127 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004128 } else {
4129 targets.emplace_back(fallbackTarget);
4130 }
4131 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004132 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004134 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004135 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004136 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004137 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004138 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004139 pointerIndex++) {
4140 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4141 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004142 if (mDragState && mDragState->dragWindow->getToken() == token &&
4143 pointerIds.test(mDragState->pointerId)) {
4144 LOG(INFO) << __func__
4145 << ": Canceling drag and drop because the pointers for the drag "
4146 "window are being canceled.";
4147 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4148 mDragState.reset();
4149 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004150 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4151 ftl::Flags<InputTarget::Flags>(), pointerIds,
4152 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004153 } else {
4154 targets.emplace_back(fallbackTarget);
4155 const auto it = mDisplayInfos.find(motionEntry.displayId);
4156 if (it != mDisplayInfos.end()) {
4157 targets.back().displayTransform = it->second.transform;
4158 targets.back().setDefaultPointerTransform(it->second.transform);
4159 }
4160 }
4161 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004164 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004165 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004166 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4167 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004168 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004169 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004170 break;
4171 }
4172 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004173 case EventEntry::Type::DEVICE_RESET:
4174 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004175 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004176 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004177 break;
4178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 }
4180
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004181 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004182 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004184
hongzuo liu95785e22022-09-06 02:51:35 +00004185 // If the outbound queue was previously empty, start the dispatch cycle going.
4186 if (wasEmpty && !connection->outboundQueue.empty()) {
4187 startDispatchCycleLocked(currentTime, connection);
4188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189}
4190
Svet Ganov5d3bc372020-01-26 23:11:07 -08004191void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004192 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004193 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004194 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195 return;
4196 }
4197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004198 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004199 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004200
4201 if (downEvents.empty()) {
4202 return;
4203 }
4204
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004205 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004206 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4207 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004208 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004209
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004210 const auto [_, touchedWindowState, displayId] =
4211 findTouchStateWindowAndDisplayLocked(connection->getToken());
4212 if (touchedWindowState == nullptr) {
4213 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4214 }
4215 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004216
hongzuo liu95785e22022-09-06 02:51:35 +00004217 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004218 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004219 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004220 switch (downEventEntry->type) {
4221 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004222 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4223 if (windowHandle != nullptr) {
4224 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004225 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004226 pointerIndex++) {
4227 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4228 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004229 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4230 targetFlags, pointerIds, motionEntry.downTime,
4231 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004232 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004233 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004234 const auto it = mDisplayInfos.find(motionEntry.displayId);
4235 if (it != mDisplayInfos.end()) {
4236 targets.back().displayTransform = it->second.transform;
4237 targets.back().setDefaultPointerTransform(it->second.transform);
4238 }
4239 }
4240 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004241 break;
4242 }
4243
4244 case EventEntry::Type::KEY:
4245 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004246 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004247 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004248 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004249 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004250 case EventEntry::Type::SENSOR:
4251 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004252 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004253 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004254 break;
4255 }
4256 }
4257
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004258 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004259 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004260 }
4261
hongzuo liu95785e22022-09-06 02:51:35 +00004262 // If the outbound queue was previously empty, start the dispatch cycle going.
4263 if (wasEmpty && !connection->outboundQueue.empty()) {
4264 startDispatchCycleLocked(downTime, connection);
4265 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004266}
4267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004268std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004269 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4270 nsecs_t splitDownTime) {
4271 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272
4273 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004274 std::vector<PointerProperties> splitPointerProperties;
4275 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004277 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 uint32_t splitPointerCount = 0;
4279
4280 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004283 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004285 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004287 splitPointerProperties.push_back(pointerProperties);
4288 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 splitPointerCount += 1;
4290 }
4291 }
4292
4293 if (splitPointerCount != pointerIds.count()) {
4294 // This is bad. We are missing some of the pointers that we expected to deliver.
4295 // Most likely this indicates that we received an ACTION_MOVE events that has
4296 // different pointer ids than we expected based on the previous ACTION_DOWN
4297 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4298 // in this way.
4299 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004300 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004301 "a broken sequence of pointer ids from the input device: %s",
4302 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004303 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004306 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4309 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004310 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004312 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004314 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 if (pointerIds.count() == 1) {
4316 // The first/last pointer went down/up.
4317 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004319 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4320 ? AMOTION_EVENT_ACTION_CANCEL
4321 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 } else {
4323 // A secondary pointer went down/up.
4324 uint32_t splitPointerIndex = 0;
4325 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4326 splitPointerIndex += 1;
4327 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 action = maskedAction |
4329 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 }
4331 } else {
4332 // An unrelated pointer changed.
4333 action = AMOTION_EVENT_ACTION_MOVE;
4334 }
4335 }
4336
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004337 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4338 logDispatchStateLocked();
4339 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4340 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4341 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004342 }
4343
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004344 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004345 ATRACE_NAME_IF(ATRACE_ENABLED(),
4346 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4347 ").",
4348 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004350 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4351 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004352 originalMotionEntry.deviceId, originalMotionEntry.source,
4353 originalMotionEntry.displayId,
4354 originalMotionEntry.policyFlags, action,
4355 originalMotionEntry.actionButton,
4356 originalMotionEntry.flags, originalMotionEntry.metaState,
4357 originalMotionEntry.buttonState,
4358 originalMotionEntry.classification,
4359 originalMotionEntry.edgeFlags,
4360 originalMotionEntry.xPrecision,
4361 originalMotionEntry.yPrecision,
4362 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004363 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004364 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 return splitMotionEntry;
4367}
4368
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004369void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4370 std::scoped_lock _l(mLock);
4371 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4372}
4373
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004374void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004375 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004376 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Antonio Kantekf16f2832021-09-28 04:39:20 +00004379 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004381 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004383 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 } // release lock
4387
4388 if (needWake) {
4389 mLooper->wake();
4390 }
4391}
4392
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004393void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004394 ALOGD_IF(debugInboundEventDetails(),
4395 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4396 ", deviceId=%d, source=%s, displayId=%" PRId32
4397 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4398 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004399 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4400 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4401 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004402 Result<void> keyCheck = validateKeyEvent(args.action);
4403 if (!keyCheck.ok()) {
4404 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 return;
4406 }
4407
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004408 uint32_t policyFlags = args.policyFlags;
4409 int32_t flags = args.flags;
4410 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004411 // InputDispatcher tracks and generates key repeats on behalf of
4412 // whatever notifies it, so repeatCount should always be set to 0
4413 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4415 policyFlags |= POLICY_FLAG_VIRTUAL;
4416 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 if (policyFlags & POLICY_FLAG_FUNCTION) {
4419 metaState |= AMETA_FUNCTION_ON;
4420 }
4421
4422 policyFlags |= POLICY_FLAG_TRUSTED;
4423
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004424 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004426 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4427 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4428 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429
Michael Wright2b3c3302018-03-02 17:19:13 +00004430 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004431 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004432 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4433 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004434 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436
Antonio Kantekf16f2832021-09-28 04:39:20 +00004437 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 { // acquire lock
4439 mLock.lock();
4440
4441 if (shouldSendKeyToInputFilterLocked(args)) {
4442 mLock.unlock();
4443
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004444 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004445 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 return; // event was consumed by the filter
4447 }
4448
4449 mLock.lock();
4450 }
4451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004452 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004453 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4454 args.deviceId, args.source, args.displayId, policyFlags,
4455 args.action, flags, keyCode, args.scanCode, metaState,
4456 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004457 if (mTracer) {
4458 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004461 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 mLock.unlock();
4463 } // release lock
4464
4465 if (needWake) {
4466 mLooper->wake();
4467 }
4468}
4469
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 return mInputFilterEnabled;
4472}
4473
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004475 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004476 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004477 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004478 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4480 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4482 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4483 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4484 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4485 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004486 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004487 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4488 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004489 i, args.pointerProperties[i].id,
4490 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4491 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4492 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4493 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4494 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4495 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4496 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4497 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4498 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4499 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004502
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004503 Result<void> motionCheck =
4504 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4505 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004506 if (!motionCheck.ok()) {
4507 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4508 return;
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004511 if (DEBUG_VERIFY_EVENTS) {
4512 auto [it, _] =
4513 mVerifiersByDisplay.try_emplace(args.displayId,
4514 StringPrintf("display %" PRId32, args.displayId));
4515 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004516 it->second.processMovement(args.deviceId, args.source, args.action,
4517 args.getPointerCount(), args.pointerProperties.data(),
4518 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004519 if (!result.ok()) {
4520 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4521 }
4522 }
4523
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004524 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004526
4527 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004528 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4529 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004530 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4531 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
Antonio Kantekf16f2832021-09-28 04:39:20 +00004535 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 { // acquire lock
4537 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004538 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4539 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4540 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004541 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004542 if (touchStateIt != mTouchStatesByDisplay.end()) {
4543 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004544 if (touchState.hasTouchingPointers(args.deviceId) ||
4545 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004546 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4547 }
4548 }
4549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550
4551 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004552 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004553 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004554 displayTransform = it->second.transform;
4555 }
4556
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 mLock.unlock();
4558
4559 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004560 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4561 args.action, args.actionButton, args.flags, args.edgeFlags,
4562 args.metaState, args.buttonState, args.classification,
4563 displayTransform, args.xPrecision, args.yPrecision,
4564 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004565 args.downTime, args.eventTime, args.getPointerCount(),
4566 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567
4568 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004569 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 return; // event was consumed by the filter
4571 }
4572
4573 mLock.lock();
4574 }
4575
4576 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004577 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004578 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4579 args.deviceId, args.source, args.displayId,
4580 policyFlags, args.action, args.actionButton,
4581 args.flags, args.metaState, args.buttonState,
4582 args.classification, args.edgeFlags, args.xPrecision,
4583 args.yPrecision, args.xCursorPosition,
4584 args.yCursorPosition, args.downTime,
4585 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004586 if (mTracer) {
4587 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004590 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4591 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004592 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004593 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004594 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4595 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4596 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004597 }
4598
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004599 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 mLock.unlock();
4601 } // release lock
4602
4603 if (needWake) {
4604 mLooper->wake();
4605 }
4606}
4607
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004608void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004609 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004610 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4611 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004612 args.id, args.eventTime, args.deviceId, args.source,
4613 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004614 }
Chris Yef59a2f42020-10-16 12:55:26 -07004615
Antonio Kantekf16f2832021-09-28 04:39:20 +00004616 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004617 { // acquire lock
4618 mLock.lock();
4619
4620 // Just enqueue a new sensor event.
4621 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004622 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4623 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4624 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004625
4626 needWake = enqueueInboundEventLocked(std::move(newEntry));
4627 mLock.unlock();
4628 } // release lock
4629
4630 if (needWake) {
4631 mLooper->wake();
4632 }
4633}
4634
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004636 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004637 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4638 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004639 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004640 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004641}
4642
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004643bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004644 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645}
4646
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004647void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004648 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004649 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4650 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004651 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004654 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004656 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657}
4658
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004659void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004660 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004661 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4662 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664
Antonio Kantekf16f2832021-09-28 04:39:20 +00004665 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004667 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004669 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004670 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004671 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004672
4673 for (auto& [_, verifier] : mVerifiersByDisplay) {
4674 verifier.resetDevice(args.deviceId);
4675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 } // release lock
4677
4678 if (needWake) {
4679 mLooper->wake();
4680 }
4681}
4682
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004683void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004684 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004685 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4686 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004687 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004688
Antonio Kantekf16f2832021-09-28 04:39:20 +00004689 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004690 { // acquire lock
4691 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004692 auto entry =
4693 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004694 needWake = enqueueInboundEventLocked(std::move(entry));
4695 } // release lock
4696
4697 if (needWake) {
4698 mLooper->wake();
4699 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004700}
4701
Prabir Pradhan5735a322022-04-11 17:23:34 +00004702InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004703 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004704 InputEventInjectionSync syncMode,
4705 std::chrono::milliseconds timeout,
4706 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004707 Result<void> eventValidation = validateInputEvent(*event);
4708 if (!eventValidation.ok()) {
4709 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4710 return InputEventInjectionResult::FAILED;
4711 }
4712
Prabir Pradhan65613802023-02-22 23:36:58 +00004713 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004714 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4715 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4716 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4717 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004718 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004719 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
Prabir Pradhan5735a322022-04-11 17:23:34 +00004721 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004723 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004724 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4725 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4726 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4727 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4728 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004729 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004730 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004731 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004732 }
4733
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004734 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4735 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4736
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004737 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004739 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004740 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004741 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004742 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004743 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4744 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4745 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004746 int32_t keyCode = incomingKey.getKeyCode();
4747 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004748 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004749 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004750 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4751 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4752 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4755 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004756 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757
4758 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4759 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004760 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004761 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4762 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4763 std::to_string(t.duration().count()).c_str());
4764 }
4765 }
4766
4767 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004768 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004769 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4770 incomingKey.getEventTime(), resolvedDeviceId,
4771 incomingKey.getSource(), incomingKey.getDisplayId(),
4772 policyFlags, action, flags, keyCode,
4773 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004774 incomingKey.getRepeatCount(),
4775 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004776 if (mTracer) {
4777 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4778 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004779 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004780 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 }
4782
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004783 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004784 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004785 const bool isPointerEvent =
4786 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4787 // If a pointer event has no displayId specified, inject it to the default display.
4788 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4789 ? ADISPLAY_ID_DEFAULT
4790 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004791 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792
4793 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004794 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004796 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4797 motionEvent.getAction(), eventTime,
4798 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4800 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4801 std::to_string(t.duration().count()).c_str());
4802 }
4803 }
4804
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004805 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4806 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4807 }
4808
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004810 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004811 const size_t pointerCount = motionEvent.getPointerCount();
4812 const std::vector<PointerProperties>
4813 pointerProperties(motionEvent.getPointerProperties(),
4814 motionEvent.getPointerProperties() + pointerCount);
4815
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004816 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004817 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004818 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4819 *sampleEventTimes, resolvedDeviceId,
4820 motionEvent.getSource(), displayId, policyFlags,
4821 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004822 motionEvent.getActionButton(), flags,
4823 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004824 motionEvent.getButtonState(),
4825 motionEvent.getClassification(),
4826 motionEvent.getEdgeFlags(),
4827 motionEvent.getXPrecision(),
4828 motionEvent.getYPrecision(),
4829 motionEvent.getRawXCursorPosition(),
4830 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004831 motionEvent.getDownTime(), pointerProperties,
4832 std::vector<PointerCoords>(samplePointerCoords,
4833 samplePointerCoords +
4834 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004835 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004836 if (mTracer) {
4837 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4838 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004839 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004840 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004841 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004842 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004843 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004844 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4845 resolvedDeviceId, motionEvent.getSource(), displayId,
4846 policyFlags, motionEvent.getAction(),
4847 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004848 motionEvent.getMetaState(), motionEvent.getButtonState(),
4849 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4850 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4851 motionEvent.getRawXCursorPosition(),
4852 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4853 pointerProperties,
4854 std::vector<PointerCoords>(samplePointerCoords,
4855 samplePointerCoords +
4856 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004857 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4858 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004859 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 }
4861 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004864 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004865 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004870 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004871 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004872 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004874 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004875 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877
4878 mLock.unlock();
4879
4880 if (needWake) {
4881 mLooper->wake();
4882 }
4883
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004884 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004886 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004888 if (syncMode == InputEventInjectionSync::NONE) {
4889 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 } else {
4891 for (;;) {
4892 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004893 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 break;
4895 }
4896
4897 nsecs_t remainingTimeout = endTime - now();
4898 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004899 if (DEBUG_INJECTION) {
4900 ALOGD("injectInputEvent - Timed out waiting for injection result "
4901 "to become available.");
4902 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004903 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 break;
4905 }
4906
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 }
4909
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004910 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4911 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004913 if (DEBUG_INJECTION) {
4914 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4915 injectionState->pendingForegroundDispatches);
4916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 nsecs_t remainingTimeout = endTime - now();
4918 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004919 if (DEBUG_INJECTION) {
4920 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4921 "dispatches to finish.");
4922 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004923 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 break;
4925 }
4926
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004927 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929 }
4930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 } // release lock
4932
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004933 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004934 LOG(INFO) << "injectInputEvent - Finished with result "
4935 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937
4938 return injectionResult;
4939}
4940
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004941std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004942 std::array<uint8_t, 32> calculatedHmac;
4943 std::unique_ptr<VerifiedInputEvent> result;
4944 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004945 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004946 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4947 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4948 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004949 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004950 break;
4951 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004952 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004953 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4954 VerifiedMotionEvent verifiedMotionEvent =
4955 verifiedMotionEventFromMotionEvent(motionEvent);
4956 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004957 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004958 break;
4959 }
4960 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004961 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004962 return nullptr;
4963 }
4964 }
4965 if (calculatedHmac == INVALID_HMAC) {
4966 return nullptr;
4967 }
tyiu1573a672023-02-21 22:38:32 +00004968 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004969 return nullptr;
4970 }
4971 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004972}
4973
Prabir Pradhan24047542023-11-02 17:14:59 +00004974void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004975 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004976 if (!entry.injectionState) {
4977 // Not an injected event.
4978 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004980
4981 InjectionState& injectionState = *entry.injectionState;
4982 if (DEBUG_INJECTION) {
4983 LOG(INFO) << "Setting input event injection result to "
4984 << ftl::enum_string(injectionResult);
4985 }
4986
4987 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4988 // Log the outcome since the injector did not wait for the injection result.
4989 switch (injectionResult) {
4990 case InputEventInjectionResult::SUCCEEDED:
4991 ALOGV("Asynchronous input event injection succeeded.");
4992 break;
4993 case InputEventInjectionResult::TARGET_MISMATCH:
4994 ALOGV("Asynchronous input event injection target mismatch.");
4995 break;
4996 case InputEventInjectionResult::FAILED:
4997 ALOGW("Asynchronous input event injection failed.");
4998 break;
4999 case InputEventInjectionResult::TIMED_OUT:
5000 ALOGW("Asynchronous input event injection timed out.");
5001 break;
5002 case InputEventInjectionResult::PENDING:
5003 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5004 break;
5005 }
5006 }
5007
5008 injectionState.injectionResult = injectionResult;
5009 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010}
5011
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005012void InputDispatcher::transformMotionEntryForInjectionLocked(
5013 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005014 // Input injection works in the logical display coordinate space, but the input pipeline works
5015 // display space, so we need to transform the injected events accordingly.
5016 const auto it = mDisplayInfos.find(entry.displayId);
5017 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005018 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005019
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005020 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5021 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5022 const vec2 cursor =
5023 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5024 {entry.xCursorPosition, entry.yCursorPosition});
5025 entry.xCursorPosition = cursor.x;
5026 entry.yCursorPosition = cursor.y;
5027 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005028 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005029 entry.pointerCoords[i] =
5030 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5031 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005032 }
5033}
5034
Prabir Pradhan24047542023-11-02 17:14:59 +00005035void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005036 if (entry.injectionState) {
5037 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039}
5040
Prabir Pradhan24047542023-11-02 17:14:59 +00005041void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005042 if (entry.injectionState) {
5043 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005045 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005046 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
5048 }
5049}
5050
chaviw98318de2021-05-19 16:45:23 -05005051const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005052 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005053 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005054 auto it = mWindowHandlesByDisplay.find(displayId);
5055 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005056}
5057
chaviw98318de2021-05-19 16:45:23 -05005058sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005059 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005060 if (windowHandleToken == nullptr) {
5061 return nullptr;
5062 }
5063
Prabir Pradhan16463382023-10-12 23:03:19 +00005064 if (!displayId) {
5065 // Look through all displays.
5066 for (auto& it : mWindowHandlesByDisplay) {
5067 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5068 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5069 if (windowHandle->getToken() == windowHandleToken) {
5070 return windowHandle;
5071 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005074 return nullptr;
5075 }
5076
Prabir Pradhan16463382023-10-12 23:03:19 +00005077 // Only look through the requested display.
5078 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005079 if (windowHandle->getToken() == windowHandleToken) {
5080 return windowHandle;
5081 }
5082 }
5083 return nullptr;
5084}
5085
chaviw98318de2021-05-19 16:45:23 -05005086sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5087 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005088 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005089 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5090 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005091 if (handle->getId() == windowHandle->getId() &&
5092 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005093 if (windowHandle->getInfo()->displayId != it.first) {
5094 ALOGE("Found window %s in display %" PRId32
5095 ", but it should belong to display %" PRId32,
5096 windowHandle->getName().c_str(), it.first,
5097 windowHandle->getInfo()->displayId);
5098 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005099 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 }
5102 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005103 return nullptr;
5104}
5105
chaviw98318de2021-05-19 16:45:23 -05005106sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005107 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5108 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109}
5110
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005111ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5112 auto displayInfoIt = mDisplayInfos.find(displayId);
5113 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5114 : kIdentityTransform;
5115}
5116
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005117bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5118 const MotionEntry& motionEntry) const {
5119 const WindowInfo& info = *window->getInfo();
5120
5121 // Skip spy window targets that are not valid for targeted injection.
5122 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005123 return false;
5124 }
5125
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005126 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5127 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5128 return false;
5129 }
5130
5131 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5132 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5133 window->getName().c_str());
5134 return false;
5135 }
5136
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005137 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005138 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005139 ALOGW("Not sending touch to %s because there's no corresponding connection",
5140 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 return false;
5142 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005143
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005144 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005145 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005146 return false;
5147 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005148
5149 // Drop events that can't be trusted due to occlusion
5150 const auto [x, y] = resolveTouchedPosition(motionEntry);
5151 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5152 if (!isTouchTrustedLocked(occlusionInfo)) {
5153 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005154 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005155 for (const auto& log : occlusionInfo.debugInfo) {
5156 ALOGD("%s", log.c_str());
5157 }
5158 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005159 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5160 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005161 return false;
5162 }
5163
5164 // Drop touch events if requested by input feature
5165 if (shouldDropInput(motionEntry, window)) {
5166 return false;
5167 }
5168
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005169 // Ignore touches if stylus is down anywhere on screen
5170 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5171 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5172 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5173 return false;
5174 }
5175
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005176 return true;
5177}
5178
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005179void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005180 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5181 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005182 // Remove all handles on a display if there are no windows left.
5183 mWindowHandlesByDisplay.erase(displayId);
5184 return;
5185 }
5186
5187 // Since we compare the pointer of input window handles across window updates, we need
5188 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005189 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5190 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5191 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005192 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005193 }
5194
chaviw98318de2021-05-19 16:45:23 -05005195 std::vector<sp<WindowInfoHandle>> newHandles;
5196 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005197 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005198 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005199 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005200 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005201 const bool canReceiveInput =
5202 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5203 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005204 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005205 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005206 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005207 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005208 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005209 }
5210
5211 if (info->displayId != displayId) {
5212 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5213 handle->getName().c_str(), displayId, info->displayId);
5214 continue;
5215 }
5216
Robert Carredd13602020-04-13 17:24:34 -07005217 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5218 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005219 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005220 oldHandle->updateFrom(handle);
5221 newHandles.push_back(oldHandle);
5222 } else {
5223 newHandles.push_back(handle);
5224 }
5225 }
5226
5227 // Insert or replace
5228 mWindowHandlesByDisplay[displayId] = newHandles;
5229}
5230
Arthur Hungb92218b2018-08-14 12:00:21 +08005231/**
5232 * Called from InputManagerService, update window handle list by displayId that can receive input.
5233 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5234 * If set an empty list, remove all handles from the specific display.
5235 * For focused handle, check if need to change and send a cancel event to previous one.
5236 * For removed handle, check if need to send a cancel event if already in touch.
5237 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005239 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005240 if (DEBUG_FOCUS) {
5241 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005242 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005243 windowList += iwh->getName() + " ";
5244 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005245 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247
Prabir Pradhand65552b2021-10-07 11:23:50 -07005248 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005249 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005250 const WindowInfo& info = *window->getInfo();
5251
5252 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005253 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005254 if (noInputWindow && window->getToken() != nullptr) {
5255 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5256 window->getName().c_str());
5257 window->releaseChannel();
5258 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005259
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005260 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005261 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5262 !info.inputConfig.test(
5263 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005264 "%s has feature SPY, but is not a trusted overlay.",
5265 window->getName().c_str());
5266
Prabir Pradhand65552b2021-10-07 11:23:50 -07005267 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005268 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5269 !info.inputConfig.test(
5270 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005271 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5272 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005273 }
5274
Arthur Hung72d8dc32020-03-28 00:48:39 +00005275 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005276 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005277 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
chaviw98318de2021-05-19 16:45:23 -05005279 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005280
chaviw98318de2021-05-19 16:45:23 -05005281 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005282
Vishnu Nairc519ff72021-01-21 08:23:08 -08005283 std::optional<FocusResolver::FocusChanges> changes =
5284 mFocusResolver.setInputWindows(displayId, windowHandles);
5285 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005286 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005289 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5290 mTouchStatesByDisplay.find(displayId);
5291 if (stateIt != mTouchStatesByDisplay.end()) {
5292 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005293 for (size_t i = 0; i < state.windows.size();) {
5294 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005295 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005296 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5297 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005298 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5299 "touched window was removed");
5300 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5301 // Since we are about to drop the touch, cancel the events for the wallpaper as
5302 // well.
5303 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5304 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5305 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5306 if (const auto& ww = state.getWallpaperWindow(); ww) {
5307 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005310 state.windows.erase(state.windows.begin() + i);
5311 } else {
5312 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314 }
arthurhungb89ccb02020-12-30 16:19:01 +08005315
arthurhung6d4bed92021-03-17 11:59:33 +08005316 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005317 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005318 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005319 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005320 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005321 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5322 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005323 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005324 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005325 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005326
Arthur Hung72d8dc32020-03-28 00:48:39 +00005327 // Release information for windows that are no longer present.
5328 // This ensures that unused input channels are released promptly.
5329 // Otherwise, they might stick around until the window handle is destroyed
5330 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005331 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005332 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005333 if (DEBUG_FOCUS) {
5334 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005335 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005336 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005337 }
chaviw291d88a2019-02-14 10:33:58 -08005338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339}
5340
5341void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005342 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005343 if (DEBUG_FOCUS) {
5344 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5345 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5346 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005347 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005348 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005349 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 } // release lock
5351
5352 // Wake up poll loop since it may need to make new input dispatching choices.
5353 mLooper->wake();
5354}
5355
Vishnu Nair599f1412021-06-21 10:39:58 -07005356void InputDispatcher::setFocusedApplicationLocked(
5357 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5358 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5359 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5360
5361 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5362 return; // This application is already focused. No need to wake up or change anything.
5363 }
5364
5365 // Set the new application handle.
5366 if (inputApplicationHandle != nullptr) {
5367 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5368 } else {
5369 mFocusedApplicationHandlesByDisplay.erase(displayId);
5370 }
5371
5372 // No matter what the old focused application was, stop waiting on it because it is
5373 // no longer focused.
5374 resetNoFocusedWindowTimeoutLocked();
5375}
5376
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005377void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5378 if (interval.count() < 0) {
5379 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5380 }
5381 std::scoped_lock _l(mLock);
5382 mMinTimeBetweenUserActivityPokes = interval;
5383}
5384
Tiger Huang721e26f2018-07-24 22:26:19 +08005385/**
5386 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5387 * the display not specified.
5388 *
5389 * We track any unreleased events for each window. If a window loses the ability to receive the
5390 * released event, we will send a cancel event to it. So when the focused display is changed, we
5391 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5392 * display. The display-specified events won't be affected.
5393 */
5394void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005395 if (DEBUG_FOCUS) {
5396 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5397 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005398 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005399 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005400
5401 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005402 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005403 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005404 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005405 const auto windowHandle =
5406 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5407 if (windowHandle == nullptr) {
5408 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005409 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005410 CancelationOptions
5411 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5412 "The display which contains this window no longer has focus.");
5413 options.displayId = ADISPLAY_ID_NONE;
5414 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005415 }
5416 mFocusedDisplayId = displayId;
5417
Chris Ye3c2d6f52020-08-09 10:39:48 -07005418 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005419 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005420 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005421
Vishnu Nairad321cd2020-08-20 16:40:21 -07005422 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005423 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005424 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005425 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005426 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005427 }
5428 }
5429 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005430 } // release lock
5431
5432 // Wake up poll loop since it may need to make new input dispatching choices.
5433 mLooper->wake();
5434}
5435
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005437 if (DEBUG_FOCUS) {
5438 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440
5441 bool changed;
5442 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005443 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444
5445 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5446 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005447 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
5450 if (mDispatchEnabled && !enabled) {
5451 resetAndDropEverythingLocked("dispatcher is being disabled");
5452 }
5453
5454 mDispatchEnabled = enabled;
5455 mDispatchFrozen = frozen;
5456 changed = true;
5457 } else {
5458 changed = false;
5459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 } // release lock
5461
5462 if (changed) {
5463 // Wake up poll loop since it may need to make new input dispatching choices.
5464 mLooper->wake();
5465 }
5466}
5467
5468void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005469 if (DEBUG_FOCUS) {
5470 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472
5473 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005474 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475
5476 if (mInputFilterEnabled == enabled) {
5477 return;
5478 }
5479
5480 mInputFilterEnabled = enabled;
5481 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5482 } // release lock
5483
5484 // Wake up poll loop since there might be work to do to drop everything.
5485 mLooper->wake();
5486}
5487
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005488bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005489 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005490 bool needWake = false;
5491 {
5492 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005493 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005494 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005495 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005496 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5497 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005498 mTouchModePerDisplay.count(displayId) == 0
5499 ? "not set"
5500 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5501
Antonio Kantek15beb512022-06-13 22:35:41 +00005502 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5503 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005504 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005505 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005506 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005507 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5508 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005509 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005510 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005511 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005512 return false;
5513 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005514 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005515 mTouchModePerDisplay[displayId] = inTouchMode;
5516 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5517 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005518 needWake = enqueueInboundEventLocked(std::move(entry));
5519 } // release lock
5520
5521 if (needWake) {
5522 mLooper->wake();
5523 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005524 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005525}
5526
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005527bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005528 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5529 if (focusedToken == nullptr) {
5530 return false;
5531 }
5532 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5533 return isWindowOwnedBy(windowHandle, pid, uid);
5534}
5535
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005536bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005537 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5538 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5539 const sp<WindowInfoHandle> windowHandle =
5540 getWindowHandleLocked(connectionToken);
5541 return isWindowOwnedBy(windowHandle, pid, uid);
5542 }) != mInteractionConnectionTokens.end();
5543}
5544
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005545void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5546 if (opacity < 0 || opacity > 1) {
5547 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5548 return;
5549 }
5550
5551 std::scoped_lock lock(mLock);
5552 mMaximumObscuringOpacityForTouch = opacity;
5553}
5554
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005555std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5556InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005557 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5558 for (TouchedWindow& w : state.windows) {
5559 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005560 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005561 }
5562 }
5563 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005564 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005565}
5566
Prabir Pradhan367f3432024-02-13 23:05:58 +00005567bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5568 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005569 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005570 if (DEBUG_FOCUS) {
5571 ALOGD("Trivial transfer to same window.");
5572 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005573 return true;
5574 }
5575
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005577 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578
Arthur Hungabbb9d82021-09-01 14:52:30 +00005579 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005580 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005581
Arthur Hungabbb9d82021-09-01 14:52:30 +00005582 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005583 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 return false;
5585 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005586 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5587 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005588 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5589 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005590 return false;
5591 }
5592 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005593
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005594 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5595 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5596 if (!toWindowHandle) {
5597 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598 return false;
5599 }
5600
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005601 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005602 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005603 touchedWindow->windowHandle->getName().c_str(),
5604 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 }
5606
Arthur Hungabbb9d82021-09-01 14:52:30 +00005607 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005608 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005609 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005610 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
Arthur Hungabbb9d82021-09-01 14:52:30 +00005612 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005613 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005614 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005615 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005616 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005617 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005618 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005619 // Transferring touch focus using this API should not effect the focused window.
5620 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005621 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005622 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623
Arthur Hungabbb9d82021-09-01 14:52:30 +00005624 // Store the dragging window.
5625 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005626 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005627 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5628 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005629 return false;
5630 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005631 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005632 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005633 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 }
5635
Arthur Hungabbb9d82021-09-01 14:52:30 +00005636 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005637 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5638 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005639 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005640 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005641 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5642 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005643 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005644 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5645 newTargetFlags);
5646
5647 // Check if the wallpaper window should deliver the corresponding event.
5648 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005649 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 } // release lock
5652
5653 // Wake up poll loop since it may need to make new input dispatching choices.
5654 mLooper->wake();
5655 return true;
5656}
5657
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005658/**
5659 * Get the touched foreground window on the given display.
5660 * Return null if there are no windows touched on that display, or if more than one foreground
5661 * window is being touched.
5662 */
5663sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5664 auto stateIt = mTouchStatesByDisplay.find(displayId);
5665 if (stateIt == mTouchStatesByDisplay.end()) {
5666 ALOGI("No touch state on display %" PRId32, displayId);
5667 return nullptr;
5668 }
5669
5670 const TouchState& state = stateIt->second;
5671 sp<WindowInfoHandle> touchedForegroundWindow;
5672 // If multiple foreground windows are touched, return nullptr
5673 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005674 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005675 if (touchedForegroundWindow != nullptr) {
5676 ALOGI("Two or more foreground windows: %s and %s",
5677 touchedForegroundWindow->getName().c_str(),
5678 window.windowHandle->getName().c_str());
5679 return nullptr;
5680 }
5681 touchedForegroundWindow = window.windowHandle;
5682 }
5683 }
5684 return touchedForegroundWindow;
5685}
5686
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005687// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005688bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5689 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005690 sp<IBinder> fromToken;
5691 { // acquire lock
5692 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005693 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005694 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005695 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5696 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005697 return false;
5698 }
5699
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005700 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5701 if (from == nullptr) {
5702 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5703 return false;
5704 }
5705
5706 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005707 } // release lock
5708
Prabir Pradhan367f3432024-02-13 23:05:58 +00005709 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005710}
5711
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005713 if (DEBUG_FOCUS) {
5714 ALOGD("Resetting and dropping all events (%s).", reason);
5715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716
Michael Wrightfb04fd52022-11-24 22:31:11 +00005717 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 synthesizeCancelationEventsForAllConnectionsLocked(options);
5719
5720 resetKeyRepeatLocked();
5721 releasePendingEventLocked();
5722 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005723 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005726 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727}
5728
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005729void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 dumpDispatchStateLocked(dump);
5732
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005733 std::istringstream stream(dump);
5734 std::string line;
5735
5736 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005737 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739}
5740
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005741std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005742 std::string dump;
5743
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005744 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5745 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005746
5747 std::string windowName = "None";
5748 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005749 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005750 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5751 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5752 : "token has capture without window";
5753 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005754 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005755
5756 return dump;
5757}
5758
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005759void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005760 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5761 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5762 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005763 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764
Tiger Huang721e26f2018-07-24 22:26:19 +08005765 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5766 dump += StringPrintf(INDENT "FocusedApplications:\n");
5767 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5768 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005769 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005770 const std::chrono::duration timeout =
5771 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005772 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005773 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005774 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005777 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005779
Vishnu Nairc519ff72021-01-21 08:23:08 -08005780 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005781 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005783 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005785 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005786 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5787 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
5789 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005790 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792
arthurhung6d4bed92021-03-17 11:59:33 +08005793 if (mDragState) {
5794 dump += StringPrintf(INDENT "DragState:\n");
5795 mDragState->dump(dump, INDENT2);
5796 }
5797
Arthur Hungb92218b2018-08-14 12:00:21 +08005798 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005799 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5800 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5801 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5802 const auto& displayInfo = it->second;
5803 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5804 displayInfo.logicalHeight);
5805 displayInfo.transform.dump(dump, "transform", INDENT4);
5806 } else {
5807 dump += INDENT2 "No DisplayInfo found!\n";
5808 }
5809
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005810 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005811 dump += INDENT2 "Windows:\n";
5812 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005813 dump += StringPrintf(INDENT3 "%zu: %s", i,
5814 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005815 }
5816 } else {
5817 dump += INDENT2 "Windows: <none>\n";
5818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 }
5820 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005821 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822 }
5823
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005824 if (!mGlobalMonitorsByDisplay.empty()) {
5825 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5826 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005827 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005830 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005833 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005834
5835 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005836 if (!mRecentQueue.empty()) {
5837 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005838 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005839 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005840 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005841 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 }
5843 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005844 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 }
5846
5847 // Dump event currently being dispatched.
5848 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005849 dump += INDENT "PendingEvent:\n";
5850 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005851 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005852 dump += StringPrintf(", age=%" PRId64 "ms\n",
5853 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005855 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 }
5857
5858 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005859 if (!mInboundQueue.empty()) {
5860 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005861 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005862 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005863 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005864 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 }
5866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005867 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868 }
5869
Prabir Pradhancef936d2021-07-21 16:17:52 +00005870 if (!mCommandQueue.empty()) {
5871 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5872 } else {
5873 dump += INDENT "CommandQueue: <empty>\n";
5874 }
5875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005876 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005877 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005878 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005879 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005880 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005881 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005882 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005883 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005886 if (!connection->outboundQueue.empty()) {
5887 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5888 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005889 dump += dumpQueue(connection->outboundQueue, currentTime);
5890
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005892 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 }
5894
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005895 if (!connection->waitQueue.empty()) {
5896 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5897 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005898 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005900 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005902 std::string inputStateDump = streamableToString(connection->inputState);
5903 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005904 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005905 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907 }
5908 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005909 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 }
5911
Antonio Kantek15beb512022-06-13 22:35:41 +00005912 if (!mTouchModePerDisplay.empty()) {
5913 dump += INDENT "TouchModePerDisplay:\n";
5914 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5915 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5916 std::to_string(touchMode).c_str());
5917 }
5918 } else {
5919 dump += INDENT "TouchModePerDisplay: <none>\n";
5920 }
5921
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005922 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005923 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5924 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5925 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005926 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005927 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005928 dump += INDENT "InputTracer: ";
5929 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930}
5931
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005932void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 const size_t numMonitors = monitors.size();
5934 for (size_t i = 0; i < numMonitors; i++) {
5935 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005936 const std::shared_ptr<Connection>& connection = monitor.connection;
5937 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005938 dump += "\n";
5939 }
5940}
5941
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005942class LooperEventCallback : public LooperCallback {
5943public:
5944 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5945 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5946
5947private:
5948 std::function<int(int events)> mCallback;
5949};
5950
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005951Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005952 if (DEBUG_CHANNEL_CREATION) {
5953 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005956 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005957 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005958 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005959
5960 if (result) {
5961 return base::Error(result) << "Failed to open input channel pair with name " << name;
5962 }
5963
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005965 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005966 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005967 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005968 std::shared_ptr<Connection> connection =
5969 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5970 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005972 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5973 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005974 ALOGE("Created a new connection, but the token %p is already known", token.get());
5975 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005976
5977 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5978 this, std::placeholders::_1, token);
5979
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005980 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005981 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 } // release lock
5983
5984 // Wake the looper because some connections have changed.
5985 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005986 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987}
5988
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005989Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005990 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005991 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005992 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005993 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005994 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005995 if (result) {
5996 return base::Error(result) << "Failed to open input channel pair with name " << name;
5997 }
5998
Michael Wright3dd60e22019-03-27 22:06:44 +00005999 { // acquire lock
6000 std::scoped_lock _l(mLock);
6001
6002 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07006003 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6004 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006005 }
6006
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006007 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006008 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006009 std::shared_ptr<Connection> connection =
6010 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6011 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006012
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006013 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6014 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006015 ALOGE("Created a new connection, but the token %p is already known", token.get());
6016 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006017
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006018 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6019 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006020
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006021 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006022
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006023 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006024 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006025 }
Garfield Tan15601662020-09-22 15:32:38 -07006026
Michael Wright3dd60e22019-03-27 22:06:44 +00006027 // Wake the looper because some connections have changed.
6028 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006029 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006030}
6031
Garfield Tan15601662020-09-22 15:32:38 -07006032status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006034 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035
Harry Cutts33476232023-01-30 19:57:29 +00006036 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 if (status) {
6038 return status;
6039 }
6040 } // release lock
6041
6042 // Wake the poll loop because removing the connection may have changed the current
6043 // synchronization state.
6044 mLooper->wake();
6045 return OK;
6046}
6047
Garfield Tan15601662020-09-22 15:32:38 -07006048status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6049 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006050 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006051 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006052 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 return BAD_VALUE;
6054 }
6055
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006056 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006057
Michael Wrightd02c5b62014-02-10 15:10:22 -08006058 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006059 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 }
6061
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006062 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063
6064 nsecs_t currentTime = now();
6065 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6066
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006067 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 return OK;
6069}
6070
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006071void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006072 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6073 auto& [displayId, monitors] = *it;
6074 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006075 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006076 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006077
Michael Wright3dd60e22019-03-27 22:06:44 +00006078 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006079 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006080 } else {
6081 ++it;
6082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 }
6084}
6085
Michael Wright3dd60e22019-03-27 22:06:44 +00006086status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006087 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006088 return pilferPointersLocked(token);
6089}
Michael Wright3dd60e22019-03-27 22:06:44 +00006090
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006091status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006092 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6093 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006094 LOG(WARNING)
6095 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006096 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006097 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006098
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006099 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006100 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006101 LOG(WARNING)
6102 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6103 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006104 return BAD_VALUE;
6105 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006106 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006107 if (deviceIds.empty()) {
6108 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006109 return BAD_VALUE;
6110 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006111
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006112 for (const DeviceId deviceId : deviceIds) {
6113 TouchState& state = *statePtr;
6114 TouchedWindow& window = *windowPtr;
6115 // Send cancel events to all the input channels we're stealing from.
6116 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6117 "input channel stole pointer stream");
6118 options.deviceId = deviceId;
6119 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006120 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6121 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006122 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006123
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006124 std::string canceledWindows;
6125 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006126 if (w.windowHandle->getToken() != token) {
6127 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006128 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006129 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006130 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006131 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006132 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006133 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006134 << " is stealing input gesture for device " << deviceId << " from "
6135 << canceledWindows;
6136
6137 // Prevent the gesture from being sent to any other windows.
6138 // This only blocks relevant pointers to be sent to other windows
6139 window.addPilferingPointers(deviceId, pointerIds);
6140
6141 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006142 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006143 return OK;
6144}
6145
Prabir Pradhan99987712020-11-10 18:43:05 -08006146void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6147 { // acquire lock
6148 std::scoped_lock _l(mLock);
6149 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006150 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006151 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6152 windowHandle != nullptr ? windowHandle->getName().c_str()
6153 : "token without window");
6154 }
6155
Vishnu Nairc519ff72021-01-21 08:23:08 -08006156 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006157 if (focusedToken != windowToken) {
6158 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6159 enabled ? "enable" : "disable");
6160 return;
6161 }
6162
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006163 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006164 ALOGW("Ignoring request to %s Pointer Capture: "
6165 "window has %s requested pointer capture.",
6166 enabled ? "enable" : "disable", enabled ? "already" : "not");
6167 return;
6168 }
6169
Christine Franksb768bb42021-11-29 12:11:31 -08006170 if (enabled) {
6171 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6172 mIneligibleDisplaysForPointerCapture.end(),
6173 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6174 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6175 return;
6176 }
6177 }
6178
Prabir Pradhan99987712020-11-10 18:43:05 -08006179 setPointerCaptureLocked(enabled);
6180 } // release lock
6181
6182 // Wake the thread to process command entries.
6183 mLooper->wake();
6184}
6185
Christine Franksb768bb42021-11-29 12:11:31 -08006186void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6187 { // acquire lock
6188 std::scoped_lock _l(mLock);
6189 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6190 if (!isEligible) {
6191 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6192 }
6193 } // release lock
6194}
6195
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006196std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006197 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006198 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006199 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006200 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006201 }
6202 }
6203 }
6204 return std::nullopt;
6205}
6206
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006207std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6208 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006209 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006210 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006211 }
6212
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006213 for (const auto& [token, connection] : mConnectionsByToken) {
6214 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006215 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 }
6217 }
Robert Carr4e670e52018-08-15 13:26:12 -07006218
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006219 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220}
6221
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006222std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006223 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006224 if (connection == nullptr) {
6225 return "<nullptr>";
6226 }
6227 return connection->getInputChannelName();
6228}
6229
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006230void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006231 mAnrTracker.eraseToken(connection->getToken());
6232 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006233}
6234
Prabir Pradhancef936d2021-07-21 16:17:52 +00006235void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006236 const std::shared_ptr<Connection>& connection,
6237 uint32_t seq, bool handled,
6238 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006240 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006241
6242 { // Start critical section
6243 auto dispatchEntryIt =
6244 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6245 [seq](auto& e) { return e->seq == seq; });
6246 if (dispatchEntryIt == connection->waitQueue.end()) {
6247 return;
6248 }
6249
6250 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6251
6252 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6253 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006254 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006255 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6256 }
6257 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006258 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006259 dispatchEntry.deliveryTime, consumeTime, finishTime);
6260 }
6261
6262 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006263 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6264 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006265 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006266 }
6267 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006268
6269 // Dequeue the event and start the next cycle.
6270 // Because the lock might have been released, it is possible that the
6271 // contents of the wait queue to have been drained, so we need to double-check
6272 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006273 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6274 [seq](auto& e) { return e->seq == seq; });
6275 if (entryIt != connection->waitQueue.end()) {
6276 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6277 connection->waitQueue.erase(entryIt);
6278
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006279 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6281 if (!connection->responsive) {
6282 connection->responsive = isConnectionResponsive(*connection);
6283 if (connection->responsive) {
6284 // The connection was unresponsive, and now it's responsive.
6285 processConnectionResponsiveLocked(*connection);
6286 }
6287 }
6288 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006289 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006290 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6291 // Only dispatch fallbacks if there is a window for the connection.
6292 if (windowHandle != nullptr) {
6293 const auto inputTarget =
6294 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6295 dispatchEntry->targetFlags,
6296 fallbackKeyEntry->downTime);
6297 if (inputTarget.has_value()) {
6298 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6299 *inputTarget);
6300 }
6301 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006303 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006304 }
6305
6306 // Start the next dispatch cycle for this connection.
6307 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308}
6309
Prabir Pradhancef936d2021-07-21 16:17:52 +00006310void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6311 const sp<IBinder>& newToken) {
6312 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6313 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006314 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315 };
6316 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317}
6318
Prabir Pradhancef936d2021-07-21 16:17:52 +00006319void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6320 auto command = [this, token, x, y]() REQUIRES(mLock) {
6321 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006322 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006323 };
6324 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006325}
6326
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006327void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 if (connection == nullptr) {
6329 LOG_ALWAYS_FATAL("Caller must check for nullness");
6330 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006331 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6332 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006334 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006335 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006336 return;
6337 }
6338 /**
6339 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6340 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6341 * has changed. This could cause newer entries to time out before the already dispatched
6342 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6343 * processes the events linearly. So providing information about the oldest entry seems to be
6344 * most useful.
6345 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006346 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6347 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006348 std::string reason =
6349 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006350 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006351 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006352 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006353 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006354 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006355
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006356 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6357
6358 // Stop waking up for events on this connection, it is already unresponsive
6359 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006360}
6361
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006362void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6363 std::string reason =
6364 StringPrintf("%s does not have a focused window", application->getName().c_str());
6365 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006366
Yabin Cui8eb9c552023-06-08 18:05:07 +00006367 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006368 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006369 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006370 };
6371 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006372}
6373
chaviw98318de2021-05-19 16:45:23 -05006374void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006375 const std::string& reason) {
6376 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6377 updateLastAnrStateLocked(windowLabel, reason);
6378}
6379
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006380void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6381 const std::string& reason) {
6382 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383 updateLastAnrStateLocked(windowLabel, reason);
6384}
6385
6386void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6387 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006389 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 struct tm tm;
6391 localtime_r(&t, &tm);
6392 char timestr[64];
6393 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006394 mLastAnrState.clear();
6395 mLastAnrState += INDENT "ANR:\n";
6396 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006397 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6398 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006399 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400}
6401
Prabir Pradhancef936d2021-07-21 16:17:52 +00006402void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006403 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 const KeyEvent event = createKeyEvent(entry);
6405 nsecs_t delay = 0;
6406 { // release lock
6407 scoped_unlock unlock(mLock);
6408 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006409 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006410 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6411 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6412 std::to_string(t.duration().count()).c_str());
6413 }
6414 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415
6416 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006417 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006418 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006419 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006420 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006421 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006422 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424}
6425
Prabir Pradhancef936d2021-07-21 16:17:52 +00006426void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006427 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006428 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006429 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006430 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006431 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006432 };
6433 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006434}
6435
Prabir Pradhanedd96402022-02-15 01:46:16 -08006436void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006437 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006438 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006439 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006440 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006441 };
6442 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006443}
6444
6445/**
6446 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6447 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6448 * command entry to the command queue.
6449 */
6450void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6451 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006452 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006453 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006454 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006455 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006456 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006457 pid = findMonitorPidByTokenLocked(connectionToken);
6458 } else {
6459 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006460 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006461 reason.c_str());
6462 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6463 if (handle != nullptr) {
6464 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006465 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006466 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006467 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006468}
6469
6470/**
6471 * Tell the policy that a connection has become responsive so that it can stop ANR.
6472 */
6473void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006474 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006475 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006476 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006477 pid = findMonitorPidByTokenLocked(connectionToken);
6478 } else {
6479 // The connection is a window
6480 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6481 if (handle != nullptr) {
6482 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006483 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006484 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006485 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006486}
6487
Prabir Pradhan24047542023-11-02 17:14:59 +00006488std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006489 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006490 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006491 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006492 if (!handled) {
6493 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006494 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006495 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006496 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 // Get the fallback key state.
6500 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006501 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006502 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006503 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006504 connection->inputState.removeFallbackKey(originalKeyCode);
6505 }
6506
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006507 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508 // If the application handles the original key for which we previously
6509 // generated a fallback or if the window is not a foreground window,
6510 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006511 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006513 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6514 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6515 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6516 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6517 keyEntry.policyFlags);
6518 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006519 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006520 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521
6522 mLock.unlock();
6523
Prabir Pradhana41d2442023-04-20 21:30:40 +00006524 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006525 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6526 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006527 unhandledKeyFallback) {
6528 event = *unhandledKeyFallback;
6529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530
6531 mLock.lock();
6532
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006533 // Cancel the fallback key, but only if we still have a window for the channel.
6534 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006535 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006536 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6537 if (windowHandle != nullptr) {
6538 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6539 "application handled the original non-fallback key "
6540 "or is no longer a foreground target, "
6541 "canceling previously dispatched fallback key");
6542 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006543 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006546 connection->inputState.removeFallbackKey(originalKeyCode);
6547 }
6548 } else {
6549 // If the application did not handle a non-fallback key, first check
6550 // that we are in a good state to perform unhandled key event processing
6551 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006552 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006553 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006554 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6555 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6556 "since this is not an initial down. "
6557 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6558 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6559 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006560 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006563 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006564 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6565 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6566 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6567 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6568 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006569 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006570
6571 mLock.unlock();
6572
Prabir Pradhana41d2442023-04-20 21:30:40 +00006573 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006574 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6575 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006576 fb) {
6577 fallback = true;
6578 event = *fb;
6579 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006580
6581 mLock.lock();
6582
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006583 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006584 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006585 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006586 }
6587
6588 // Latch the fallback keycode for this key on an initial down.
6589 // The fallback keycode cannot change at any other point in the lifecycle.
6590 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006592 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006593 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006594 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006595 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006596 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006597 }
6598
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006599 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006600
6601 // Cancel the fallback key if the policy decides not to send it anymore.
6602 // We will continue to dispatch the key to the policy but we will no
6603 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006604 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6605 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006606 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6607 if (fallback) {
6608 ALOGD("Unhandled key event: Policy requested to send key %d"
6609 "as a fallback for %d, but on the DOWN it had requested "
6610 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006611 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006612 } else {
6613 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6614 "but on the DOWN it had requested to send %d. "
6615 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006616 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006617 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006619
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006620 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6621 if (windowHandle != nullptr) {
6622 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6623 "canceling fallback, policy no longer desires it");
6624 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006625 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006626 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006627
6628 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006630 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006631 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006632 }
6633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006634
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006635 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6636 {
6637 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006638 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006639 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006640 for (const auto& [key, value] : fallbackKeys) {
6641 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006642 }
6643 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6644 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006645 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006646 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006647
6648 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006649 // Return the fallback key that we want dispatched to the channel.
6650 std::unique_ptr<KeyEntry> newEntry =
6651 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6652 event.getEventTime(), event.getDeviceId(),
6653 event.getSource(), event.getDisplayId(),
6654 keyEntry.policyFlags, keyEntry.action,
6655 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6656 *fallbackKeyCode, event.getScanCode(),
6657 event.getMetaState(), event.getRepeatCount(),
6658 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006659 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6660 ALOGD("Unhandled key event: Dispatching fallback key. "
6661 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006662 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006663 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006664 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006665 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006666 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6667 ALOGD("Unhandled key event: No fallback key.");
6668 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006669
6670 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006671 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 }
6673 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006674 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675}
6676
Michael Wrightd02c5b62014-02-10 15:10:22 -08006677void InputDispatcher::traceInboundQueueLengthLocked() {
6678 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006679 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006680 }
6681}
6682
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006683void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006684 if (ATRACE_ENABLED()) {
6685 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006686 snprintf(counterName, sizeof(counterName), "oq:%s",
6687 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006688 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006689 }
6690}
6691
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006692void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 if (ATRACE_ENABLED()) {
6694 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006695 snprintf(counterName, sizeof(counterName), "wq:%s",
6696 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006697 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006698 }
6699}
6700
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006701void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006702 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006703
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006704 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006705 dumpDispatchStateLocked(dump);
6706
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006707 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006708 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006709 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006710 }
6711}
6712
6713void InputDispatcher::monitor() {
6714 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006715 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006716 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006717 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006718}
6719
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006720/**
6721 * Wake up the dispatcher and wait until it processes all events and commands.
6722 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6723 * this method can be safely called from any thread, as long as you've ensured that
6724 * the work you are interested in completing has already been queued.
6725 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006726bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006727 /**
6728 * Timeout should represent the longest possible time that a device might spend processing
6729 * events and commands.
6730 */
6731 constexpr std::chrono::duration TIMEOUT = 100ms;
6732 std::unique_lock lock(mLock);
6733 mLooper->wake();
6734 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6735 return result == std::cv_status::no_timeout;
6736}
6737
Vishnu Naire798b472020-07-23 13:52:21 -07006738/**
6739 * Sets focus to the window identified by the token. This must be called
6740 * after updating any input window handles.
6741 *
6742 * Params:
6743 * request.token - input channel token used to identify the window that should gain focus.
6744 * request.focusedToken - the token that the caller expects currently to be focused. If the
6745 * specified token does not match the currently focused window, this request will be dropped.
6746 * If the specified focused token matches the currently focused window, the call will succeed.
6747 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6748 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6749 * when requesting the focus change. This determines which request gets
6750 * precedence if there is a focus change request from another source such as pointer down.
6751 */
Vishnu Nair958da932020-08-21 17:12:37 -07006752void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6753 { // acquire lock
6754 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006755 std::optional<FocusResolver::FocusChanges> changes =
6756 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6757 if (changes) {
6758 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006759 }
6760 } // release lock
6761 // Wake up poll loop since it may need to make new input dispatching choices.
6762 mLooper->wake();
6763}
6764
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006765void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6766 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006767 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006768 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6769 ? removedFocusedWindowHandle
6770 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6771 if (resolvedWindow == nullptr) {
6772 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006773 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006774 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6775 "focus left window");
6776 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6777 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006778 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006779 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006780 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006781 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006782 }
6783
Prabir Pradhan99987712020-11-10 18:43:05 -08006784 // If a window has pointer capture, then it must have focus. We need to ensure that this
6785 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6786 // If the window loses focus before it loses pointer capture, then the window can be in a state
6787 // where it has pointer capture but not focus, violating the contract. Therefore we must
6788 // dispatch the pointer capture event before the focus event. Since focus events are added to
6789 // the front of the queue (above), we add the pointer capture event to the front of the queue
6790 // after the focus events are added. This ensures the pointer capture event ends up at the
6791 // front.
6792 disablePointerCaptureForcedLocked();
6793
Vishnu Nairc519ff72021-01-21 08:23:08 -08006794 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006795 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006796 }
6797}
Vishnu Nair958da932020-08-21 17:12:37 -07006798
Prabir Pradhan99987712020-11-10 18:43:05 -08006799void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006800 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006801 return;
6802 }
6803
6804 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6805
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006806 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006807 setPointerCaptureLocked(false);
6808 }
6809
6810 if (!mWindowTokenWithPointerCapture) {
6811 // No need to send capture changes because no window has capture.
6812 return;
6813 }
6814
6815 if (mPendingEvent != nullptr) {
6816 // Move the pending event to the front of the queue. This will give the chance
6817 // for the pending event to be dropped if it is a captured event.
6818 mInboundQueue.push_front(mPendingEvent);
6819 mPendingEvent = nullptr;
6820 }
6821
6822 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006823 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006824 mInboundQueue.push_front(std::move(entry));
6825}
6826
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006827void InputDispatcher::setPointerCaptureLocked(bool enable) {
6828 mCurrentPointerCaptureRequest.enable = enable;
6829 mCurrentPointerCaptureRequest.seq++;
6830 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006831 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006832 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006833 };
6834 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006835}
6836
Vishnu Nair599f1412021-06-21 10:39:58 -07006837void InputDispatcher::displayRemoved(int32_t displayId) {
6838 { // acquire lock
6839 std::scoped_lock _l(mLock);
6840 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006841 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006842 setFocusedApplicationLocked(displayId, nullptr);
6843 // Call focus resolver to clean up stale requests. This must be called after input windows
6844 // have been removed for the removed display.
6845 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006846 // Reset pointer capture eligibility, regardless of previous state.
6847 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006848 // Remove the associated touch mode state.
6849 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006850 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006851 } // release lock
6852
6853 // Wake up poll loop since it may need to make new input dispatching choices.
6854 mLooper->wake();
6855}
6856
Patrick Williamsd828f302023-04-28 17:52:08 -05006857void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006858 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6859 {
6860 // acquire lock
6861 std::scoped_lock _l(mLock);
6862 logDispatchStateLocked();
6863 }
6864 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6865 result.error().message().c_str());
6866 };
chaviw15fab6f2021-06-07 14:15:52 -05006867 // The listener sends the windows as a flattened array. Separate the windows by display for
6868 // more convenient parsing.
6869 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006870 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006871 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006872 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006873 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006874
6875 { // acquire lock
6876 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006877
6878 // Ensure that we have an entry created for all existing displays so that if a displayId has
6879 // no windows, we can tell that the windows were removed from the display.
6880 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6881 handlesPerDisplay[displayId];
6882 }
6883
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006884 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006885 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006886 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6887 }
6888
6889 for (const auto& [displayId, handles] : handlesPerDisplay) {
6890 setInputWindowsLocked(handles, displayId);
6891 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006892
6893 if (update.vsyncId < mWindowInfosVsyncId) {
6894 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6895 ", current update vsync id: %" PRId64,
6896 mWindowInfosVsyncId, update.vsyncId);
6897 }
6898 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006899 }
6900 // Wake up poll loop since it may need to make new input dispatching choices.
6901 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006902}
6903
Vishnu Nair062a8672021-09-03 16:07:44 -07006904bool InputDispatcher::shouldDropInput(
6905 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006906 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6907 (windowHandle->getInfo()->inputConfig.test(
6908 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006909 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006910 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6911 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006912 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006913 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006914 windowHandle->getInfo()->displayId);
6915 return true;
6916 }
6917 return false;
6918}
6919
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006920void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006921 const gui::WindowInfosUpdate& update) {
6922 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006923}
6924
Arthur Hungdfd528e2021-12-08 13:23:04 +00006925void InputDispatcher::cancelCurrentTouch() {
6926 {
6927 std::scoped_lock _l(mLock);
6928 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006929 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006930 "cancel current touch");
6931 synthesizeCancelationEventsForAllConnectionsLocked(options);
6932
6933 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006934 }
6935 // Wake up poll loop since there might be work to do.
6936 mLooper->wake();
6937}
6938
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006939void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6940 std::scoped_lock _l(mLock);
6941 mMonitorDispatchingTimeout = timeout;
6942}
6943
Arthur Hungc539dbb2022-12-08 07:45:36 +00006944void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6945 const sp<WindowInfoHandle>& oldWindowHandle,
6946 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006947 TouchState& state, int32_t deviceId,
6948 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006949 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006950 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006951 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6952 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6953 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6954 newWindowHandle->getInfo()->inputConfig.test(
6955 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6956 const sp<WindowInfoHandle> oldWallpaper =
6957 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6958 const sp<WindowInfoHandle> newWallpaper =
6959 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6960 if (oldWallpaper == newWallpaper) {
6961 return;
6962 }
6963
6964 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006965 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006966 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006967 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006968 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006969 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006970 }
6971
6972 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006973 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6974 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006975 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006976 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006977 }
6978}
6979
6980void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6981 ftl::Flags<InputTarget::Flags> newTargetFlags,
6982 const sp<WindowInfoHandle> fromWindowHandle,
6983 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006984 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006985 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006986 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6987 fromWindowHandle->getInfo()->inputConfig.test(
6988 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6989 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6990 toWindowHandle->getInfo()->inputConfig.test(
6991 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6992
6993 const sp<WindowInfoHandle> oldWallpaper =
6994 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6995 const sp<WindowInfoHandle> newWallpaper =
6996 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6997 if (oldWallpaper == newWallpaper) {
6998 return;
6999 }
7000
7001 if (oldWallpaper != nullptr) {
7002 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
7003 "transferring touch focus to another window");
7004 state.removeWindowByToken(oldWallpaper->getToken());
7005 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7006 }
7007
7008 if (newWallpaper != nullptr) {
7009 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007010 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7011 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007012 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7013 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007014 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007015 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007016 std::shared_ptr<Connection> wallpaperConnection =
7017 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007018 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007019 std::shared_ptr<Connection> toConnection =
7020 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007021 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7022 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7023 wallpaperFlags);
7024 }
7025 }
7026}
7027
7028sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7029 const sp<WindowInfoHandle>& windowHandle) const {
7030 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7031 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7032 bool foundWindow = false;
7033 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7034 if (!foundWindow && otherHandle != windowHandle) {
7035 continue;
7036 }
7037 if (windowHandle == otherHandle) {
7038 foundWindow = true;
7039 continue;
7040 }
7041
7042 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7043 return otherHandle;
7044 }
7045 }
7046 return nullptr;
7047}
7048
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007049void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7050 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007051 std::scoped_lock _l(mLock);
7052
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007053 mConfig.keyRepeatTimeout = timeout.count();
7054 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007055}
7056
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007057bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7058 DeviceId deviceId, int32_t pointerId) {
7059 std::scoped_lock _l(mLock);
7060 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7061 if (touchStateIt == mTouchStatesByDisplay.end()) {
7062 return false;
7063 }
7064 for (const TouchedWindow& window : touchStateIt->second.windows) {
7065 if (window.windowHandle->getToken() == token &&
7066 (window.hasTouchingPointer(deviceId, pointerId) ||
7067 window.hasHoveringPointer(deviceId, pointerId))) {
7068 return true;
7069 }
7070 }
7071 return false;
7072}
7073
Garfield Tane84e6f92019-08-29 17:28:41 -07007074} // namespace android::inputdispatcher