blob: 55976137c58782f7271431c5243f61d5307415f6 [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
Linnan Li5e5645e2024-03-05 14:43:05 +0000576// Returns true if the given window's frame can occlude pointer events at the given display
577// location.
578bool windowOccludesTouchAt(const WindowInfo& windowInfo, int displayId, float x, float y,
579 const ui::Transform& displayTransform) {
580 if (windowInfo.displayId != displayId) {
581 return false;
582 }
583 const auto frame = displayTransform.transform(windowInfo.frame);
584 const auto p = floor(displayTransform.transform(x, y));
585 return p.x >= frame.left && p.x < frame.right && p.y >= frame.top && p.y < frame.bottom;
586}
587
Prabir Pradhand65552b2021-10-07 11:23:50 -0700588bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
589 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000590 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700591}
592
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800593// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000594// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
595// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
596// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800597// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000598bool canReceiveForegroundTouches(const WindowInfo& info) {
599 // A non-touchable window can still receive touch events (e.g. in the case of
600 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
601 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
602}
603
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000604bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700605 if (windowHandle == nullptr) {
606 return false;
607 }
608 const WindowInfo* windowInfo = windowHandle->getInfo();
609 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
610 return true;
611 }
612 return false;
613}
614
Prabir Pradhan5735a322022-04-11 17:23:34 +0000615// Checks targeted injection using the window's owner's uid.
616// Returns an empty string if an entry can be sent to the given window, or an error message if the
617// entry is a targeted injection whose uid target doesn't match the window owner.
618std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
619 const EventEntry& entry) {
620 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
621 // The event was not injected, or the injected event does not target a window.
622 return {};
623 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000624 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000625 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000626 return StringPrintf("No valid window target for injection into uid %s.",
627 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000628 }
629 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000630 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
631 "owned by uid %s.",
632 uid.toString().c_str(), window->getName().c_str(),
633 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000634 }
635 return {};
636}
637
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000638std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700639 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
640 // Always dispatch mouse events to cursor position.
641 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000642 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700643 }
644
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700645 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000646 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
647 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700648}
649
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700650std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
651 if (eventEntry.type == EventEntry::Type::KEY) {
652 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
653 return keyEntry.downTime;
654 } else if (eventEntry.type == EventEntry::Type::MOTION) {
655 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
656 return motionEntry.downTime;
657 }
658 return std::nullopt;
659}
660
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000661/**
662 * Compare the old touch state to the new touch state, and generate the corresponding touched
663 * windows (== input targets).
664 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
665 * If the pointer just entered the new window, produce HOVER_ENTER.
666 * For pointers remaining in the window, produce HOVER_MOVE.
667 */
668std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
669 const TouchState& newTouchState,
670 const MotionEntry& entry) {
671 std::vector<TouchedWindow> out;
672 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700673
674 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
675 // ACTION_SCROLL events should not affect the hovering pointer dispatch
676 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 }
678
679 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800680 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000681
682 std::set<sp<WindowInfoHandle>> oldWindows;
683 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800684 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 }
686
687 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800688 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000689
690 // If the pointer is no longer in the new window set, send HOVER_EXIT.
691 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
692 if (newWindows.find(oldWindow) == newWindows.end()) {
693 TouchedWindow touchedWindow;
694 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000695 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000696 out.push_back(touchedWindow);
697 }
698 }
699
700 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
701 TouchedWindow touchedWindow;
702 touchedWindow.windowHandle = newWindow;
703 if (oldWindows.find(newWindow) == oldWindows.end()) {
704 // Any windows that have this pointer now, and didn't have it before, should get
705 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000706 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000707 } else {
708 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700709 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700710 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000711 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
712 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700713 // The Accessibility injected touch exploration event stream
714 // has known inconsistencies, so log ERROR instead of
715 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700716 severity = android::base::LogSeverity::ERROR;
717 }
718 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700719 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000720 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000721 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800722 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000723 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
724 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
725 }
726 out.push_back(touchedWindow);
727 }
728 return out;
729}
730
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800731template <typename T>
732std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
733 left.insert(left.end(), right.begin(), right.end());
734 return left;
735}
736
Harry Cuttsb166c002023-05-09 13:06:05 +0000737// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
738// both.
739void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
740 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
741 if (!window.windowHandle->getInfo()->inputConfig.test(
742 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
743 // In addition to TouchState, erase this window from the input targets! We don't have a
744 // good way to do this today except by adding a nested loop.
745 // TODO(b/282025641): simplify this code once InputTargets are being identified
746 // separately from TouchedWindows.
747 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800748 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000749 });
750 return true;
751 }
752 return false;
753 });
754}
755
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700756/**
757 * In general, touch should be always split between windows. Some exceptions:
758 * 1. Don't split touch if all of the below is true:
759 * (a) we have an active pointer down *and*
760 * (b) a new pointer is going down that's from the same device *and*
761 * (c) the window that's receiving the current pointer does not support split touch.
762 * 2. Don't split mouse events
763 */
764bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
765 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
766 // We should never split mouse events
767 return false;
768 }
769 for (const TouchedWindow& touchedWindow : touchState.windows) {
770 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
771 // Spy windows should not affect whether or not touch is split.
772 continue;
773 }
774 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
775 continue;
776 }
777 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
778 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
779 // Wallpaper window should not affect whether or not touch is split
780 continue;
781 }
782
783 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
784 return false;
785 }
786 }
787 return true;
788}
789
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700790/**
791 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
792 */
793bool isStylusActiveInDisplay(
794 int32_t displayId,
795 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
796 const auto it = touchStatesByDisplay.find(displayId);
797 if (it == touchStatesByDisplay.end()) {
798 return false;
799 }
800 const TouchState& state = it->second;
801 return state.hasActiveStylus();
802}
803
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800804Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
805 struct HashFunction {
806 size_t operator()(const WindowInfo& info) const { return info.id; }
807 };
808
809 std::unordered_set<WindowInfo, HashFunction> windowSet;
810 for (const WindowInfo& info : update.windowInfos) {
811 const auto [_, inserted] = windowSet.insert(info);
812 if (!inserted) {
813 return Error() << "Duplicate entry for " << info;
814 }
815 }
816 return {};
817}
818
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800819int32_t getUserActivityEventType(const EventEntry& eventEntry) {
820 switch (eventEntry.type) {
821 case EventEntry::Type::KEY: {
822 return USER_ACTIVITY_EVENT_BUTTON;
823 }
824 case EventEntry::Type::MOTION: {
825 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
826 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
827 return USER_ACTIVITY_EVENT_TOUCH;
828 }
829 return USER_ACTIVITY_EVENT_OTHER;
830 }
831 default: {
832 LOG_ALWAYS_FATAL("%s events are not user activity",
833 ftl::enum_string(eventEntry.type).c_str());
834 }
835 }
836}
837
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000838std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
839 CancelationOptions::Mode mode) {
840 switch (mode) {
841 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
842 return {true, true};
843 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
844 return {true, false};
845 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
846 return {false, true};
847 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
848 return {false, true};
849 }
850}
851
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000852} // namespace
853
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854// --- InputDispatcher ---
855
Prabir Pradhana41d2442023-04-20 21:30:40 +0000856InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000857 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000858
859InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
860 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700861 : mPolicy(policy),
862 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700863 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800864 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800865 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700866 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800867 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700868 mDispatchEnabled(false),
869 mDispatchFrozen(false),
870 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100871 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000872 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800873 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000874 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000875 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700876 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800877 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700879 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700880#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700881 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700882#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700883 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000884
885 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000886 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000887 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800888
889 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890}
891
892InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000893 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
Prabir Pradhancef936d2021-07-21 16:17:52 +0000895 resetKeyRepeatLocked();
896 releasePendingEventLocked();
897 drainInboundQueueLocked();
898 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000900 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700901 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800902 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
904}
905
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700906status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700907 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700908 return ALREADY_EXISTS;
909 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700910 mThread = std::make_unique<InputThread>(
911 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
912 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700913}
914
915status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700916 if (mThread && mThread->isCallingThread()) {
917 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700918 return INVALID_OPERATION;
919 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700920 mThread.reset();
921 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700922}
923
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700925 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800927 std::scoped_lock _l(mLock);
928 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929
930 // Run a dispatch loop if there are no pending commands.
931 // The dispatch loop might enqueue commands to run afterwards.
932 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800933 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
935
936 // Run all pending commands if there are any.
937 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000938 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700939 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800941
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 // If we are still waiting for ack on some events,
943 // we might have to wake up earlier to check if an app is anr'ing.
944 const nsecs_t nextAnrCheck = processAnrsLocked();
945 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
946
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800947 // We are about to enter an infinitely long sleep, because we have no commands or
948 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700949 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800950 mDispatcherEnteredIdle.notify_all();
951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 } // release lock
953
954 // Wait for callback or timeout or wake. (make sure we round up, not down)
955 nsecs_t currentTime = now();
956 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
957 mLooper->pollOnce(timeoutMillis);
958}
959
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700960/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500961 * Raise ANR if there is no focused window.
962 * Before the ANR is raised, do a final state check:
963 * 1. The currently focused application must be the same one we are waiting for.
964 * 2. Ensure we still don't have a focused window.
965 */
966void InputDispatcher::processNoFocusedWindowAnrLocked() {
967 // Check if the application that we are waiting for is still focused.
968 std::shared_ptr<InputApplicationHandle> focusedApplication =
969 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
970 if (focusedApplication == nullptr ||
971 focusedApplication->getApplicationToken() !=
972 mAwaitedFocusedApplication->getApplicationToken()) {
973 // Unexpected because we should have reset the ANR timer when focused application changed
974 ALOGE("Waited for a focused window, but focused application has already changed to %s",
975 focusedApplication->getName().c_str());
976 return; // The focused application has changed.
977 }
978
chaviw98318de2021-05-19 16:45:23 -0500979 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500980 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
981 if (focusedWindowHandle != nullptr) {
982 return; // We now have a focused window. No need for ANR.
983 }
984 onAnrLocked(mAwaitedFocusedApplication);
985}
986
987/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700988 * Check if any of the connections' wait queues have events that are too old.
989 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
990 * Return the time at which we should wake up next.
991 */
992nsecs_t InputDispatcher::processAnrsLocked() {
993 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700994 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700995 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
996 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
997 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500998 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700999 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001000 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -07001001 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001002 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -05001003 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
1005 }
1006 }
1007
1008 // Check if any connection ANRs are due
1009 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
1010 if (currentTime < nextAnrCheck) { // most likely scenario
1011 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1012 }
1013
1014 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001015 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001016 if (connection == nullptr) {
1017 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1018 return nextAnrCheck;
1019 }
1020 connection->responsive = false;
1021 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001022 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001023 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001024 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025}
1026
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001027std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001028 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001029 if (connection->monitor) {
1030 return mMonitorDispatchingTimeout;
1031 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001032 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001034 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001035 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001036 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037}
1038
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001039void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 nsecs_t currentTime = now();
1041
Jeff Browndc5992e2014-04-11 01:27:26 -07001042 // Reset the key repeat timer whenever normal dispatch is suspended while the
1043 // device is in a non-interactive state. This is to ensure that we abort a key
1044 // repeat if the device is just coming out of sleep.
1045 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 resetKeyRepeatLocked();
1047 }
1048
1049 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1050 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001051 if (DEBUG_FOCUS) {
1052 ALOGD("Dispatch frozen. Waiting some more.");
1053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 return;
1055 }
1056
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 // Ready to start a new event.
1058 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001060 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 // Synthesize a key repeat if appropriate.
1062 if (mKeyRepeatState.lastKeyEntry) {
1063 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1064 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1065 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001066 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068 }
1069
1070 // Nothing to do if there is no pending event.
1071 if (!mPendingEvent) {
1072 return;
1073 }
1074 } else {
1075 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 mPendingEvent = mInboundQueue.front();
1077 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 traceInboundQueueLengthLocked();
1079 }
1080
1081 // Poke user activity for this event.
1082 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086
1087 // Now we have an event to dispatch.
1088 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001089 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 }
1097
1098 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001099 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
1101
1102 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001104 const ConfigurationChangedEntry& typedEntry =
1105 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 break;
1109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001111 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 const DeviceResetEntry& typedEntry =
1113 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001119 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001120 std::shared_ptr<const FocusEntry> typedEntry =
1121 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001122 dispatchFocusLocked(currentTime, typedEntry);
1123 done = true;
1124 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1125 break;
1126 }
1127
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001128 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001129 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001130 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1131 done = true;
1132 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1133 break;
1134 }
1135
Prabir Pradhan99987712020-11-10 18:43:05 -08001136 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1137 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001138 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1140 done = true;
1141 break;
1142 }
1143
arthurhungb89ccb02020-12-30 16:19:01 +08001144 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001145 std::shared_ptr<const DragEntry> typedEntry =
1146 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001147 dispatchDragLocked(currentTime, typedEntry);
1148 done = true;
1149 break;
1150 }
1151
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001153 std::shared_ptr<const KeyEntry> keyEntry =
1154 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001155 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001158 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1159 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001162 if (done && mTracer) {
1163 ensureEventTraced(*keyEntry);
1164 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 break;
1167 }
1168
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001169 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001170 std::shared_ptr<const MotionEntry> motionEntry =
1171 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001173 // The event is stale. However, only drop stale events if there isn't an ongoing
1174 // gesture. That would allow us to complete the processing of the current stroke.
1175 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1176 if (touchStateIt != mTouchStatesByDisplay.end()) {
1177 const TouchState& touchState = touchStateIt->second;
1178 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1179 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1180 dropReason = DropReason::STALE;
1181 }
1182 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001184 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001185 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1186 // Only drop events that are focus-dispatched.
1187 dropReason = DropReason::BLOCKED;
1188 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001189 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001190 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001191 if (done && mTracer) {
1192 ensureEventTraced(*motionEntry);
1193 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1194 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
Chris Yef59a2f42020-10-16 12:55:26 -07001197
1198 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001199 std::shared_ptr<const SensorEntry> sensorEntry =
1200 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001201
Chris Yef59a2f42020-10-16 12:55:26 -07001202 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1203 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1204 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1205 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1206 dropReason = DropReason::STALE;
1207 }
1208 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1209 done = true;
1210 break;
1211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213
1214 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
Michael Wright3a981722015-06-10 15:26:13 +01001218 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
1220 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001221 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223}
1224
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001225bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001226 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001227}
1228
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001229/**
1230 * Return true if the events preceding this incoming motion event should be dropped
1231 * Return false otherwise (the default behaviour)
1232 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001233bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001234 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001235 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001236
1237 // Optimize case where the current application is unresponsive and the user
1238 // decides to touch a window in a different application.
1239 // If the application takes too long to catch up then we drop all events preceding
1240 // the touch into the other window.
1241 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001242 const int32_t displayId = motionEntry.displayId;
1243 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001244 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001245
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001246 sp<WindowInfoHandle> touchedWindowHandle =
1247 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001248 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001249 touchedWindowHandle->getApplicationToken() !=
1250 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001251 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001252 ALOGI("Pruning input queue because user touched a different application while waiting "
1253 "for %s",
1254 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 return true;
1256 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001257
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001258 // Alternatively, maybe there's a spy window that could handle this event.
1259 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1260 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1261 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001262 const std::shared_ptr<Connection> connection =
1263 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001264 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001265 // This spy window could take more input. Drop all events preceding this
1266 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001267 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001268 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001269 mAwaitedFocusedApplication->getName().c_str());
1270 return true;
1271 }
1272 }
1273 }
1274
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001275 return false;
1276}
1277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001279 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001281 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 traceInboundQueueLengthLocked();
1283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001285 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001286 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1287 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001290 if (mTracer) {
1291 ensureEventTraced(keyEntry);
1292 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001293
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001294 // If a new up event comes in, and the pending event with same key code has been asked
1295 // to try again later because of the policy. We have to reset the intercept key wake up
1296 // time for it may have been handled in the policy and could be dropped.
1297 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1298 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001299 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001300 if (pendingKey.keyCode == keyEntry.keyCode &&
1301 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001302 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1303 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001304 pendingKey.interceptKeyWakeupTime = 0;
1305 needWake = true;
1306 }
1307 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 break;
1309 }
1310
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001311 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001312 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1313 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001314 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1315 if (mTracer) {
1316 ensureEventTraced(motionEntry);
1317 }
1318 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001319 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001320 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001322
1323 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1324 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1325 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1326 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1327 // and some other events have not yet been processed, the dispatcher will wait for
1328 // these events to be processed before dispatching the key event. This is because
1329 // the unprocessed events may cause the focus to change (for example, by launching a
1330 // new window or tapping a different window). To prevent waiting too long, we force
1331 // the key to be sent to the currently focused window when a new tap comes in.
1332 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1333 "just send the pending key event to the currently focused window.");
1334 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001335 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001336 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001339 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001340 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1341 break;
1342 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001343 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001346 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001347 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1348 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001349 // nothing to do
1350 break;
1351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353
1354 return needWake;
1355}
1356
Prabir Pradhan24047542023-11-02 17:14:59 +00001357void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001358 // Do not store sensor event in recent queue to avoid flooding the queue.
1359 if (entry->type != EventEntry::Type::SENSOR) {
1360 mRecentQueue.push_back(entry);
1361 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001362 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001363 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365}
1366
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001367sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1368 bool isStylus,
1369 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001371 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001372 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001373 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001374 continue;
1375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001377 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001378 if (!info.isSpy() &&
1379 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001380 return windowHandle;
1381 }
1382 }
1383 return nullptr;
1384}
1385
1386std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001387 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001388 if (touchedWindow == nullptr) {
1389 return {};
1390 }
1391 // Traverse windows from front to back until we encounter the touched window.
1392 std::vector<InputTarget> outsideTargets;
1393 const auto& windowHandles = getWindowHandlesLocked(displayId);
1394 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1395 if (windowHandle == touchedWindow) {
1396 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1397 // below the touched window will not get ACTION_OUTSIDE event.
1398 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001399 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001400
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001401 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001402 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001403 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1404 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001405 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1406 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001407 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 }
1409 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001410 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411}
1412
Prabir Pradhand65552b2021-10-07 11:23:50 -07001413std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001414 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001415 // Traverse windows from front to back and gather the touched spy windows.
1416 std::vector<sp<WindowInfoHandle>> spyWindows;
1417 const auto& windowHandles = getWindowHandlesLocked(displayId);
1418 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1419 const WindowInfo& info = *windowHandle->getInfo();
1420
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001421 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001422 continue;
1423 }
1424 if (!info.isSpy()) {
1425 // The first touched non-spy window was found, so return the spy windows touched so far.
1426 return spyWindows;
1427 }
1428 spyWindows.push_back(windowHandle);
1429 }
1430 return spyWindows;
1431}
1432
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 const char* reason;
1435 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001436 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001437 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001438 ALOGD("Dropped event because policy consumed it.");
1439 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 reason = "inbound event was dropped because the policy consumed it";
1441 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001442 case DropReason::DISABLED:
1443 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 ALOGI("Dropped event because input dispatch is disabled.");
1445 }
1446 reason = "inbound event was dropped because input dispatch is disabled";
1447 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001448 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001449 LOG(INFO) << "Dropping because the current application is not responding and the user "
1450 "has started interacting with a different application: "
1451 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001452 reason = "inbound event was dropped because the current application is not responding "
1453 "and the user has started interacting with a different application";
1454 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001455 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 ALOGI("Dropped event because it is stale.");
1457 reason = "inbound event was dropped because it is stale";
1458 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001459 case DropReason::NO_POINTER_CAPTURE:
1460 ALOGI("Dropped event because there is no window with Pointer Capture.");
1461 reason = "inbound event was dropped because there is no window with Pointer Capture";
1462 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001463 case DropReason::NOT_DROPPED: {
1464 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 }
1468
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001470 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001471 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001472 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1473 options.displayId = keyEntry.displayId;
1474 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001478 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1480 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001481 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001482 options.displayId = motionEntry.displayId;
1483 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 synthesizeCancelationEventsForAllConnectionsLocked(options);
1485 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001486 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1487 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001488 options.displayId = motionEntry.displayId;
1489 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 synthesizeCancelationEventsForAllConnectionsLocked(options);
1491 }
1492 break;
1493 }
Chris Yef59a2f42020-10-16 12:55:26 -07001494 case EventEntry::Type::SENSOR: {
1495 break;
1496 }
arthurhungb89ccb02020-12-30 16:19:01 +08001497 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1498 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001499 break;
1500 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001501 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001502 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001503 case EventEntry::Type::CONFIGURATION_CHANGED:
1504 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001505 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001506 break;
1507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509}
1510
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001512 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513}
1514
Prabir Pradhancef936d2021-07-21 16:17:52 +00001515bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001516 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 return false;
1518 }
1519
1520 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001521 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001522 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001523 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1524 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001525 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 return true;
1527}
1528
Prabir Pradhancef936d2021-07-21 16:17:52 +00001529void InputDispatcher::postCommandLocked(Command&& command) {
1530 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531}
1532
1533void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001534 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001535 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001536 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 releaseInboundEventLocked(entry);
1538 }
1539 traceInboundQueueLengthLocked();
1540}
1541
1542void InputDispatcher::releasePendingEventLocked() {
1543 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547}
1548
Prabir Pradhan24047542023-11-02 17:14:59 +00001549void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001550 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001551 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001552 if (DEBUG_DISPATCH_CYCLE) {
1553 ALOGD("Injected inbound event was dropped.");
1554 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 }
1557 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001558 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 }
1560 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561}
1562
1563void InputDispatcher::resetKeyRepeatLocked() {
1564 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001565 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 }
1567}
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001570 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571
Michael Wright2e732952014-09-24 13:26:59 -07001572 uint32_t policyFlags = entry->policyFlags &
1573 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001576 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1577 currentTime, entry->deviceId, entry->source,
1578 entry->displayId, policyFlags, entry->action, entry->flags,
1579 entry->keyCode, entry->scanCode, entry->metaState,
1580 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001582 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001583 if (mTracer) {
1584 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1585 }
1586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590}
1591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001592bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001594 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1595 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
1598 // Reset key repeating in case a keyboard device was added or removed or something.
1599 resetKeyRepeatLocked();
1600
1601 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001602 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1603 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001604 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001605 };
1606 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 return true;
1608}
1609
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001610bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1611 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001612 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1613 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1614 entry.deviceId);
1615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616
liushenxiang42232912021-05-21 20:24:09 +08001617 // Reset key repeating in case a keyboard device was disabled or enabled.
1618 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1619 resetKeyRepeatLocked();
1620 }
1621
Michael Wrightfb04fd52022-11-24 22:31:11 +00001622 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001623 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001625
1626 // Remove all active pointers from this device
1627 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1628 touchState.removeAllPointersForDevice(entry.deviceId);
1629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 return true;
1631}
1632
Vishnu Nairad321cd2020-08-20 16:40:21 -07001633void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001634 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001635 if (mPendingEvent != nullptr) {
1636 // Move the pending event to the front of the queue. This will give the chance
1637 // for the pending event to get dispatched to the newly focused window
1638 mInboundQueue.push_front(mPendingEvent);
1639 mPendingEvent = nullptr;
1640 }
1641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642 std::unique_ptr<FocusEntry> focusEntry =
1643 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1644 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001645
1646 // This event should go to the front of the queue, but behind all other focus events
1647 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001648 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1649 [](const std::shared_ptr<const EventEntry>& event) {
1650 return event->type == EventEntry::Type::FOCUS;
1651 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001652
1653 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001655}
1656
Prabir Pradhan24047542023-11-02 17:14:59 +00001657void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1658 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001659 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1660 if (connection == nullptr) {
1661 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001662 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001663 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001664 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001665 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001666 std::string reason = std::string("reason=").append(entry->reason);
1667 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001668 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001669}
1670
Prabir Pradhan99987712020-11-10 18:43:05 -08001671void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001672 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001673 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001674 dropReason = DropReason::NOT_DROPPED;
1675
Prabir Pradhan99987712020-11-10 18:43:05 -08001676 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001677 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001678
1679 if (entry->pointerCaptureRequest.enable) {
1680 // Enable Pointer Capture.
1681 if (haveWindowWithPointerCapture &&
1682 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001683 // This can happen if pointer capture is disabled and re-enabled before we notify the
1684 // app of the state change, so there is no need to notify the app.
1685 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1686 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001687 }
1688 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001689 // This can happen if a window requests capture and immediately releases capture.
1690 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001691 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001692 return;
1693 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001694 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1695 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1696 return;
1697 }
1698
Vishnu Nairc519ff72021-01-21 08:23:08 -08001699 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001700 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1701 mWindowTokenWithPointerCapture = token;
1702 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001703 // Disable Pointer Capture.
1704 // We do not check if the sequence number matches for requests to disable Pointer Capture
1705 // for two reasons:
1706 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1707 // to disable capture with the same sequence number: one generated by
1708 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1709 // Capture being disabled in InputReader.
1710 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1711 // actual Pointer Capture state that affects events being generated by input devices is
1712 // in InputReader.
1713 if (!haveWindowWithPointerCapture) {
1714 // Pointer capture was already forcefully disabled because of focus change.
1715 dropReason = DropReason::NOT_DROPPED;
1716 return;
1717 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001718 token = mWindowTokenWithPointerCapture;
1719 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001720 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001721 setPointerCaptureLocked(false);
1722 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001723 }
1724
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001725 auto connection = getConnectionLocked(token);
1726 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001727 // Window has gone away, clean up Pointer Capture state.
1728 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001729 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001730 setPointerCaptureLocked(false);
1731 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001732 return;
1733 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001734 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001735 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001736
1737 dropReason = DropReason::NOT_DROPPED;
1738}
1739
Prabir Pradhan24047542023-11-02 17:14:59 +00001740void InputDispatcher::dispatchTouchModeChangeLocked(
1741 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001742 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001743 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001744 if (windowHandles.empty()) {
1745 return;
1746 }
1747 const std::vector<InputTarget> inputTargets =
1748 getInputTargetsFromWindowHandlesLocked(windowHandles);
1749 if (inputTargets.empty()) {
1750 return;
1751 }
1752 entry->dispatchInProgress = true;
1753 dispatchEventLocked(currentTime, entry, inputTargets);
1754}
1755
1756std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1757 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1758 std::vector<InputTarget> inputTargets;
1759 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001760 const sp<IBinder>& token = handle->getToken();
1761 if (token == nullptr) {
1762 continue;
1763 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001764 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1765 if (connection == nullptr) {
1766 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001767 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001768 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001769 }
1770 return inputTargets;
1771}
1772
Prabir Pradhan24047542023-11-02 17:14:59 +00001773bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001774 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 if (!entry->dispatchInProgress) {
1777 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1778 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1779 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1780 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001781 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 // We have seen two identical key downs in a row which indicates that the device
1783 // driver is automatically generating key repeats itself. We take note of the
1784 // repeat here, but we disable our own next key repeat timer since it is clear that
1785 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001786 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1787 // Make sure we don't get key down from a different device. If a different
1788 // device Id has same key pressed down, the new device Id will replace the
1789 // current one to hold the key repeat with repeat count reset.
1790 // In the future when got a KEY_UP on the device id, drop it and do not
1791 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1793 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001794 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 } else {
1796 // Not a repeat. Save key down state in case we do see a repeat later.
1797 resetKeyRepeatLocked();
1798 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1799 }
1800 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001801 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1802 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001803 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001804 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001805 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1806 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001807 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 resetKeyRepeatLocked();
1809 }
1810
1811 if (entry->repeatCount == 1) {
1812 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1813 } else {
1814 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1815 }
1816
1817 entry->dispatchInProgress = true;
1818
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
1821
1822 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001823 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001825 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 return false; // wait until next wakeup
1827 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001828 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 entry->interceptKeyWakeupTime = 0;
1830 }
1831
1832 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001833 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001835 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001836 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001837
1838 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1839 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1840 };
1841 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001842 // Poke user activity for keys not passed to user
1843 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 return false; // wait for the command to run
1845 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001846 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001848 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001849 if (*dropReason == DropReason::NOT_DROPPED) {
1850 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852 }
1853
1854 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001855 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001856 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1858 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001859 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001860 // Poke user activity for undispatched keys
1861 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 return true;
1863 }
1864
1865 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001866 InputEventInjectionResult injectionResult;
1867 sp<WindowInfoHandle> focusedWindow =
1868 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1869 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001870 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return false;
1872 }
1873
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001874 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 return true;
1877 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001878 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1879
1880 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001881 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1882 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001884 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001885 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001887 if (mTracer) {
1888 ensureEventTraced(*entry);
1889 for (const auto& target : inputTargets) {
1890 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1891 }
1892 }
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 // Dispatch the key.
1895 dispatchEventLocked(currentTime, entry, inputTargets);
1896 return true;
1897}
1898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001899void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001900 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1901 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1902 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1903 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1904 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1905 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1906 entry.metaState, entry.repeatCount, entry.downTime);
1907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908}
1909
Prabir Pradhancef936d2021-07-21 16:17:52 +00001910void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001911 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001912 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001913 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1914 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1915 "source=0x%x, sensorType=%s",
1916 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001917 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001918 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001919 auto command = [this, entry]() REQUIRES(mLock) {
1920 scoped_unlock unlock(mLock);
1921
1922 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001923 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001924 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001925 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1926 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001927 };
1928 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001929}
1930
1931bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001932 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1933 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001934 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001935 }
Chris Yef59a2f42020-10-16 12:55:26 -07001936 { // acquire lock
1937 std::scoped_lock _l(mLock);
1938
1939 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001940 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001941 if (entry->type == EventEntry::Type::SENSOR) {
1942 it = mInboundQueue.erase(it);
1943 releaseInboundEventLocked(entry);
1944 }
1945 }
1946 }
1947 return true;
1948}
1949
Prabir Pradhan24047542023-11-02 17:14:59 +00001950bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1951 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001952 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001955 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 entry->dispatchInProgress = true;
1957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001958 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960
1961 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001962 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001963 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001964 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1965 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 return true;
1967 }
1968
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001969 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
1971 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001972 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001974 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 if (isPointerEvent) {
1976 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001977
1978 if (mDragState &&
1979 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1980 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1981 pilferPointersLocked(mDragState->dragWindow->getToken());
1982 }
1983
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001984 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001985 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001986 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1987 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 } else {
1989 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001990 sp<WindowInfoHandle> focusedWindow =
1991 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1992 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1993 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001994 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1995 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1996 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 return false;
2001 }
2002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002003 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00002004 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002005 return true;
2006 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002007 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002008 CancelationOptions::Mode mode(
2009 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
2010 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002011 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002012 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002013 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 return true;
2015 }
2016
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002017 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002020 if (mTracer) {
2021 ensureEventTraced(*entry);
2022 for (const auto& target : inputTargets) {
2023 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2024 }
2025 }
2026
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 dispatchEventLocked(currentTime, entry, inputTargets);
2029 return true;
2030}
2031
chaviw98318de2021-05-19 16:45:23 -05002032void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002033 bool isExiting, const int32_t rawX,
2034 const int32_t rawY) {
2035 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002036 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002037 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2038 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002039
2040 enqueueInboundEventLocked(std::move(dragEntry));
2041}
2042
Prabir Pradhan24047542023-11-02 17:14:59 +00002043void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2044 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002045 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2046 if (connection == nullptr) {
2047 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002048 }
arthurhungb89ccb02020-12-30 16:19:01 +08002049 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002050 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002051}
2052
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002053void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002054 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002055 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002056 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002057 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002058 "metaState=0x%x, buttonState=0x%x,"
2059 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002060 prefix, entry.eventTime, entry.deviceId,
2061 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2062 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2063 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2064 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002066 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002067 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002068 "x=%f, y=%f, pressure=%f, size=%f, "
2069 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2070 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002071 i, entry.pointerProperties[i].id,
2072 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002073 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2074 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2075 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2076 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2077 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2078 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2079 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2080 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2081 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084}
2085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002086void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002087 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002088 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002089 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002090 if (DEBUG_DISPATCH_CYCLE) {
2091 ALOGD("dispatchEventToCurrentInputTargets");
2092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002094 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002095
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2097
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002098 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002100 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002101 std::shared_ptr<Connection> connection = inputTarget.connection;
2102 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
2104}
2105
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002106void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2108 // If the policy decides to close the app, we will get a channel removal event via
2109 // unregisterInputChannel, and will clean up the connection that way. We are already not
2110 // sending new pointers to the connection when it blocked, but focused events will continue to
2111 // pile up.
2112 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002113 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002114 if (connection->status != Connection::Status::NORMAL) {
2115 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002117 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2118 "application not responding");
2119
2120 sp<WindowInfoHandle> windowHandle;
2121 if (!connection->monitor) {
2122 windowHandle = getWindowHandleLocked(connection->getToken());
2123 if (windowHandle == nullptr) {
2124 // The window that is receiving this ANR was removed, so there is no need to generate
2125 // cancellations, because the cancellations would have already been generated when
2126 // the window was removed.
2127 return;
2128 }
2129 }
2130 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131}
2132
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002133void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002134 if (DEBUG_FOCUS) {
2135 ALOGD("Resetting ANR timeouts.");
2136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137
2138 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002140 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141}
2142
Tiger Huang721e26f2018-07-24 22:26:19 +08002143/**
2144 * Get the display id that the given event should go to. If this event specifies a valid display id,
2145 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2146 * Focused display is the display that the user most recently interacted with.
2147 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002148int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002149 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002150 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002151 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002152 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2153 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 break;
2155 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002156 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002157 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2158 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 break;
2160 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002161 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002162 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002163 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002164 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002165 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002166 case EventEntry::Type::SENSOR:
2167 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002168 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 return ADISPLAY_ID_NONE;
2170 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002171 }
2172 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2173}
2174
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2176 const char* focusedWindowName) {
2177 if (mAnrTracker.empty()) {
2178 // already processed all events that we waited for
2179 mKeyIsWaitingForEventsTimeout = std::nullopt;
2180 return false;
2181 }
2182
2183 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2184 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002185 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002186 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002187 std::chrono::duration_cast<std::chrono::nanoseconds>(
2188 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002189 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 return true;
2191 }
2192
2193 // We still have pending events, and already started the timer
2194 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2195 return true; // Still waiting
2196 }
2197
2198 // Waited too long, and some connection still hasn't processed all motions
2199 // Just send the key to the focused window
2200 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2201 focusedWindowName);
2202 mKeyIsWaitingForEventsTimeout = std::nullopt;
2203 return false;
2204}
2205
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002207 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002208 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002209 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210
Tiger Huang721e26f2018-07-24 22:26:19 +08002211 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002212 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002213 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002214 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2215
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 // If there is no currently focused window and no focused application
2217 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002218 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2219 ALOGI("Dropping %s event because there is no focused window or focused application in "
2220 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002221 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002222 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
2224
Vishnu Nair062a8672021-09-03 16:07:44 -07002225 // Drop key events if requested by input feature
2226 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002228 }
2229
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002230 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2231 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2232 // start interacting with another application via touch (app switch). This code can be removed
2233 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2234 // an app is expected to have a focused window.
2235 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2236 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2237 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002238 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2239 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2240 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002242 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 ALOGW("Waiting because no window has focus but %s may eventually add a "
2244 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002245 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002246 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002247 outInjectionResult = InputEventInjectionResult::PENDING;
2248 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2250 // Already raised ANR. Drop the event
2251 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002252 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002254 } else {
2255 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002256 outInjectionResult = InputEventInjectionResult::PENDING;
2257 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002258 }
2259 }
2260
2261 // we have a valid, non-null focused window
2262 resetNoFocusedWindowTimeoutLocked();
2263
Prabir Pradhan5735a322022-04-11 17:23:34 +00002264 // Verify targeted injection.
2265 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2266 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002267 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2268 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002271 if (focusedWindowHandle->getInfo()->inputConfig.test(
2272 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002274 outInjectionResult = InputEventInjectionResult::PENDING;
2275 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002276 }
2277
2278 // If the event is a key event, then we must wait for all previous events to
2279 // complete before delivering it because previous events may have the
2280 // side-effect of transferring focus to a different window and we want to
2281 // ensure that the following keys are sent to the new window.
2282 //
2283 // Suppose the user touches a button in a window then immediately presses "A".
2284 // If the button causes a pop-up window to appear then we want to ensure that
2285 // the "A" key is delivered to the new pop-up window. This is because users
2286 // often anticipate pending UI changes when typing on a keyboard.
2287 // To obtain this behavior, we must serialize key events with respect to all
2288 // prior input events.
2289 if (entry.type == EventEntry::Type::KEY) {
2290 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002291 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002292 outInjectionResult = InputEventInjectionResult::PENDING;
2293 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002297 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2298 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299}
2300
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002301/**
2302 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2303 * that are currently unresponsive.
2304 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002305std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2306 const std::vector<Monitor>& monitors) const {
2307 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002308 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002309 [](const Monitor& monitor) REQUIRES(mLock) {
2310 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002311 if (!connection->responsive) {
2312 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002313 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002314 return false;
2315 }
2316 return true;
2317 });
2318 return responsiveMonitors;
2319}
2320
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002321std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002322 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002323 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002324 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002326 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 // For security reasons, we defer updating the touch state until we are sure that
2328 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 const int32_t displayId = entry.displayId;
2330 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002331 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
2333 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002334 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 // Copy current touch state into tempTouchState.
2337 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2338 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002339 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002340 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002341 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2342 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002343 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002344 }
2345
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002346 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002347
2348 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2349 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2350 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002351 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2352 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002353 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002354 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2355 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002356 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2357 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2358 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002359 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002360
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002361 if (newGesture) {
2362 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002363 }
2364
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002365 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2366 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2367 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 }
2369
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002370 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002371 if (wasDown) {
2372 // Started hovering, but the device is already down: reject the hover event
2373 LOG(ERROR) << "Got hover event " << entry.getDescription()
2374 << " but the device is already down " << oldState->dump();
2375 outInjectionResult = InputEventInjectionResult::FAILED;
2376 return {};
2377 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002378 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2379 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002380 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002381 }
2382
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2384 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002385 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002386 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002387 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002388 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2389 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002390 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002391 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002392 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002393
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002394 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002395 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002398 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002399 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002401 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002402 }
2403
Prabir Pradhan5735a322022-04-11 17:23:34 +00002404 // Verify targeted injection.
2405 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2406 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002407 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002408 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002409 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002410 }
2411
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002413 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002414 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2415 // New window supports splitting, but we should never split mouse events.
2416 isSplit = !isFromMouse;
2417 } else if (isSplit) {
2418 // New window does not support splitting but we have already split events.
2419 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002420 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2421 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002422 newTouchedWindowHandle = nullptr;
2423 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 } else {
2425 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002426 // be delivered to a new window which supports split touch. Pointers from a mouse device
2427 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002428 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002429 }
2430
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002431 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002432 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002433 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002434 // Process the foreground window first so that it is the first to receive the event.
2435 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 }
2437
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002438 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002439 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2440 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002441 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002442 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002443 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002444 }
2445
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002446 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002447 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002448 continue;
2449 }
2450
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002451 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002452 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002453 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002454 }
2455
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002456 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002457 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002458
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002459 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2460 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002461 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002462 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002463
2464 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002465 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002466 }
2467 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002468 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002469 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002470 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002471 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002472
2473 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002474
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002475 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002476 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2477 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002478 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002479 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002480 isDownOrPointerDown
2481 ? std::make_optional(entry.eventTime)
2482 : std::nullopt);
2483 // If this is the pointer going down and the touched window has a wallpaper
2484 // then also add the touched wallpaper windows so they are locked in for the
2485 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2486 // SCROLL because the wallpaper engine only supports touch events. We would need to
2487 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2488 // handle these events.
2489 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002490 windowHandle->getInfo()->inputConfig.test(
2491 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2492 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2493 if (wallpaper != nullptr) {
2494 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2495 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002496 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002497 if (isSplit) {
2498 wallpaperFlags |= InputTarget::Flags::SPLIT;
2499 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002500 tempTouchState.addOrUpdateWindow(wallpaper,
2501 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002502 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002503 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002504 }
2505 }
2506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002508
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002509 // If a window is already pilfering some pointers, give it this new pointer as well and
2510 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2511 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002512 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002513 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002514 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002515 // This window is already pilfering some pointers, and this new pointer is also
2516 // going to it. Therefore, take over this pointer and don't give it to anyone
2517 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002518 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002519 }
2520 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002521
2522 // Restrict all pilfered pointers to the pilfering windows.
2523 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 } else {
2525 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2526
2527 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002528 if (!tempTouchState.isDown(entry.deviceId) &&
2529 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002530 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2531 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2532 << " is not down or we previously dropped the pointer down event in "
2533 << "display " << displayId << ": " << entry.getDescription();
2534 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002535 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002536 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 }
2538
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002539 // If the pointer is not currently hovering, then ignore the event.
2540 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2541 const int32_t pointerId = entry.pointerProperties[0].id;
2542 if (oldState == nullptr ||
2543 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2544 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2545 "display "
2546 << displayId << ": " << entry.getDescription();
2547 outInjectionResult = InputEventInjectionResult::FAILED;
2548 return {};
2549 }
2550 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2551 }
2552
arthurhung6d4bed92021-03-17 11:59:33 +08002553 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002554
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002556 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002557 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002558 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002559 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002560 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002561 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002562 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002563 sp<WindowInfoHandle> newTouchedWindowHandle =
2564 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002565
Prabir Pradhan5735a322022-04-11 17:23:34 +00002566 // Verify targeted injection.
2567 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2568 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002569 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002570 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002571 }
2572
Linnan Libf069a32024-02-29 17:22:59 +00002573 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002574 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002575 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002576 newTouchedWindowHandle = nullptr;
2577 }
2578
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002579 if (newTouchedWindowHandle != nullptr &&
2580 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002581 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002582 oldTouchedWindowHandle->getName().c_str(),
2583 newTouchedWindowHandle->getName().c_str(), displayId);
2584
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002586 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002587 const PointerProperties& pointer = entry.pointerProperties[0];
2588 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002589
2590 const TouchedWindow& touchedWindow =
2591 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002592 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002593 InputTarget::DispatchMode::SLIPPERY_EXIT,
2594 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002595 touchedWindow.getDownTimeInTarget(entry.deviceId),
2596 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597
2598 // Make a slippery entrance into the new window.
2599 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002600 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002603 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002604 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002605 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002608 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
2610 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002611 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002612 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002613 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002616 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2617 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002618 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002619 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002620
2621 // Check if the wallpaper window should deliver the corresponding event.
2622 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002623 tempTouchState, entry.deviceId, pointer, targets);
2624 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002625 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 }
2627 }
Arthur Hung96483742022-11-15 03:30:48 +00002628
2629 // Update the pointerIds for non-splittable when it received pointer down.
2630 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2631 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002632 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002633 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2634 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002635 // Ignore drag window for it should just track one pointer.
2636 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2637 continue;
2638 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002639 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002640 }
2641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
2643
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002644 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002645 {
2646 std::vector<TouchedWindow> hoveringWindows =
2647 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2648 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002649 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002650 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2651 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002652 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002653 if (!target) {
2654 continue;
2655 }
2656 // Hardcode to single hovering pointer for now.
2657 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2658 pointerIds.set(entry.pointerProperties[0].id);
2659 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2660 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663
Prabir Pradhan5735a322022-04-11 17:23:34 +00002664 // Ensure that all touched windows are valid for injection.
2665 if (entry.injectionState != nullptr) {
2666 std::string errs;
2667 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002668 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2669 if (err) errs += "\n - " + *err;
2670 }
2671 if (!errs.empty()) {
2672 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002673 "%s:%s",
2674 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002675 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002676 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002677 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002678 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002679
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002680 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2681 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002683 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002684 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002685 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002686 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002687 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002688 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002689 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002690 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002691 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2692 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 }
2695 }
2696 }
2697 }
2698
Harry Cuttsb166c002023-05-09 13:06:05 +00002699 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2700 // only want the system UI to handle these gestures.
2701 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2702 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2703 if (isTouchpadNavGesture) {
2704 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2705 }
2706
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002707 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002708 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002709 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002710 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002711 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002712 continue;
2713 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002714 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002715 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002716 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002717 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002718
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002719 // During targeted injection, only allow owned targets to receive events
2720 std::erase_if(targets, [&](const InputTarget& target) {
2721 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2722 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2723 if (err) {
2724 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2725 << ": " << (*err);
2726 return true;
2727 }
2728 return false;
2729 });
2730
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002731 if (targets.empty()) {
2732 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2733 outInjectionResult = InputEventInjectionResult::FAILED;
2734 return {};
2735 }
2736
2737 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2738 // window that is actually receiving the entire gesture.
2739 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002740 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002741 })) {
2742 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2743 << entry.getDescription();
2744 outInjectionResult = InputEventInjectionResult::FAILED;
2745 return {};
2746 }
2747
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002748 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749
Prabir Pradhan502a7252023-12-01 16:11:24 +00002750 // Now that we have generated all of the input targets for this event, reset the dispatch
2751 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002752 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002753 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002754 }
2755
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002756 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002757 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002758 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002759 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002760 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002761 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002762 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002763 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2764 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002765 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2766 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2767 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 }
2769
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002770 // Save changes unless the action was scroll in which case the temporary touch
2771 // state was only valid for this one action.
2772 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002773 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002774 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002775 mTouchStatesByDisplay[displayId] = tempTouchState;
2776 } else {
2777 mTouchStatesByDisplay.erase(displayId);
2778 }
2779 }
2780
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002781 if (tempTouchState.windows.empty()) {
2782 mTouchStatesByDisplay.erase(displayId);
2783 }
2784
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002785 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786}
2787
arthurhung6d4bed92021-03-17 11:59:33 +08002788void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002789 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2790 // have an explicit reason to support it.
2791 constexpr bool isStylus = false;
2792
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002793 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002794 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002795 if (dropWindow) {
2796 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002797 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002798 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002799 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002800 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002801 }
2802 mDragState.reset();
2803}
2804
2805void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002806 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002807 return;
2808 }
2809
arthurhung6d4bed92021-03-17 11:59:33 +08002810 if (!mDragState->isStartDrag) {
2811 mDragState->isStartDrag = true;
2812 mDragState->isStylusButtonDownAtStart =
2813 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2814 }
2815
Arthur Hung54745652022-04-20 07:17:41 +00002816 // Find the pointer index by id.
2817 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002818 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002819 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2820 if (pointerProperties.id == mDragState->pointerId) {
2821 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002822 }
Arthur Hung54745652022-04-20 07:17:41 +00002823 }
arthurhung6d4bed92021-03-17 11:59:33 +08002824
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002825 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002826 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002827 }
2828
2829 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2830 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2831 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2832
2833 switch (maskedAction) {
2834 case AMOTION_EVENT_ACTION_MOVE: {
2835 // Handle the special case : stylus button no longer pressed.
2836 bool isStylusButtonDown =
2837 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2838 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2839 finishDragAndDrop(entry.displayId, x, y);
2840 return;
2841 }
2842
2843 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2844 // until we have an explicit reason to support it.
2845 constexpr bool isStylus = false;
2846
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002847 sp<WindowInfoHandle> hoverWindowHandle =
2848 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2849 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002850 // enqueue drag exit if needed.
2851 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2852 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2853 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002854 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002855 y);
2856 }
2857 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2858 }
2859 // enqueue drag location if needed.
2860 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002861 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002862 }
2863 break;
2864 }
2865
2866 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002867 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002868 break;
2869 }
2870 // The drag pointer is up.
2871 [[fallthrough]];
2872 case AMOTION_EVENT_ACTION_UP:
2873 finishDragAndDrop(entry.displayId, x, y);
2874 break;
2875 case AMOTION_EVENT_ACTION_CANCEL: {
2876 ALOGD("Receiving cancel when drag and drop.");
2877 sendDropWindowCommandLocked(nullptr, 0, 0);
2878 mDragState.reset();
2879 break;
2880 }
arthurhungb89ccb02020-12-30 16:19:01 +08002881 }
2882}
2883
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002884std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2885 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002886 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002887 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002888 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2889 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002890 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2891 return {};
2892 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002893 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002894 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002895 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002896 inputTarget.flags = targetFlags;
2897 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2898 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2899 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2900 if (displayInfoIt != mDisplayInfos.end()) {
2901 inputTarget.displayTransform = displayInfoIt->second.transform;
2902 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002903 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002904 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2905 }
2906 return inputTarget;
2907}
2908
chaviw98318de2021-05-19 16:45:23 -05002909void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002910 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002911 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002912 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002913 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002914 std::vector<InputTarget>::iterator it =
2915 std::find_if(inputTargets.begin(), inputTargets.end(),
2916 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002917 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002918 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002919
chaviw98318de2021-05-19 16:45:23 -05002920 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002921
2922 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002923 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002924 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2925 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002926 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002927 return;
2928 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002929 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002930 it = inputTargets.end() - 1;
2931 }
2932
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002933 if (it->flags != targetFlags) {
2934 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2935 }
2936 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2937 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2938 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2939 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002940}
2941
2942void InputDispatcher::addPointerWindowTargetLocked(
2943 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002944 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2945 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2946 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002947 if (pointerIds.none()) {
2948 for (const auto& target : inputTargets) {
2949 LOG(INFO) << "Target: " << target;
2950 }
2951 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2952 return;
2953 }
2954 std::vector<InputTarget>::iterator it =
2955 std::find_if(inputTargets.begin(), inputTargets.end(),
2956 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002957 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002958 });
2959
2960 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2961 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2962 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2963 // input targets for hovering pointers and for touching pointers.
2964 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2965 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002966 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002967 // Force the code below to create a new input target
2968 it = inputTargets.end();
2969 }
2970
2971 const WindowInfo* windowInfo = windowHandle->getInfo();
2972
2973 if (it == inputTargets.end()) {
2974 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002975 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2976 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002977 if (!target) {
2978 return;
2979 }
2980 inputTargets.push_back(*target);
2981 it = inputTargets.end() - 1;
2982 }
2983
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002984 if (it->dispatchMode != dispatchMode) {
2985 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2986 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2987 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002988 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002989 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2990 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002991 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002992 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002993 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002994 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2995 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002996
chaviw1ff3d1e2020-07-01 15:53:47 -07002997 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998}
2999
Michael Wright3dd60e22019-03-27 22:06:44 +00003000void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07003001 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003002 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
3003 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00003004
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003005 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003006 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003007 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
3008 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003009 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
3010 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003011 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003012 target.setDefaultPointerTransform(target.displayTransform);
3013 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
3015}
3016
Robert Carrc9bf1d32020-04-13 17:21:08 -07003017/**
3018 * Indicate whether one window handle should be considered as obscuring
3019 * another window handle. We only check a few preconditions. Actually
3020 * checking the bounds is left to the caller.
3021 */
chaviw98318de2021-05-19 16:45:23 -05003022static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3023 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003024 // Compare by token so cloned layers aren't counted
3025 if (haveSameToken(windowHandle, otherHandle)) {
3026 return false;
3027 }
3028 auto info = windowHandle->getInfo();
3029 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003030 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003031 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003032 } else if (otherInfo->alpha == 0 &&
3033 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003034 // Those act as if they were invisible, so we don't need to flag them.
3035 // We do want to potentially flag touchable windows even if they have 0
3036 // opacity, since they can consume touches and alter the effects of the
3037 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003038 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003039 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3040 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003041 } else if (info->ownerUid == otherInfo->ownerUid) {
3042 // If ownerUid is the same we don't generate occlusion events as there
3043 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003044 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003045 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003046 return false;
3047 } else if (otherInfo->displayId != info->displayId) {
3048 return false;
3049 }
3050 return true;
3051}
3052
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003053/**
3054 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3055 * untrusted, one should check:
3056 *
3057 * 1. If result.hasBlockingOcclusion is true.
3058 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3059 * BLOCK_UNTRUSTED.
3060 *
3061 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3062 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3063 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3064 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3065 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3066 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3067 *
3068 * If neither of those is true, then it means the touch can be allowed.
3069 */
3070InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
Linnan Li5e5645e2024-03-05 14:43:05 +00003071 const sp<WindowInfoHandle>& windowHandle, float x, float y) const {
chaviw98318de2021-05-19 16:45:23 -05003072 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003073 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003074 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003075 TouchOcclusionInfo info;
3076 info.hasBlockingOcclusion = false;
3077 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003078 info.obscuringUid = gui::Uid::INVALID;
3079 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003080 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003081 if (windowHandle == otherHandle) {
3082 break; // All future windows are below us. Exit early.
3083 }
chaviw98318de2021-05-19 16:45:23 -05003084 const WindowInfo* otherInfo = otherHandle->getInfo();
Linnan Li5e5645e2024-03-05 14:43:05 +00003085 if (canBeObscuredBy(windowHandle, otherHandle) &&
3086 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId)) &&
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003087 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003088 if (DEBUG_TOUCH_OCCLUSION) {
3089 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003090 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003091 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003092 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3093 // we perform the checks below to see if the touch can be propagated or not based on the
3094 // window's touch occlusion mode
3095 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3096 info.hasBlockingOcclusion = true;
3097 info.obscuringUid = otherInfo->ownerUid;
3098 info.obscuringPackage = otherInfo->packageName;
3099 break;
3100 }
3101 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003102 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003103 float opacity =
3104 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3105 // Given windows A and B:
3106 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3107 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3108 opacityByUid[uid] = opacity;
3109 if (opacity > info.obscuringOpacity) {
3110 info.obscuringOpacity = opacity;
3111 info.obscuringUid = uid;
3112 info.obscuringPackage = otherInfo->packageName;
3113 }
3114 }
3115 }
3116 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003117 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003118 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003119 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003120 return info;
3121}
3122
chaviw98318de2021-05-19 16:45:23 -05003123std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003124 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003125 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003126 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3127 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3128 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003129 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003130 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003131 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3132 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003133 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3134 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3135 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003136 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003137}
3138
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003139bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3140 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003141 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3142 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003143 return false;
3144 }
3145 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003146 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003147 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003148 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003149 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3150 return false;
3151 }
3152 return true;
3153}
3154
chaviw98318de2021-05-19 16:45:23 -05003155bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Linnan Li5e5645e2024-03-05 14:43:05 +00003156 float x, float y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003158 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3159 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003160 if (windowHandle == otherHandle) {
3161 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
chaviw98318de2021-05-19 16:45:23 -05003163 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003164 if (canBeObscuredBy(windowHandle, otherHandle) &&
Linnan Li5e5645e2024-03-05 14:43:05 +00003165 windowOccludesTouchAt(*otherInfo, displayId, x, y, getTransformLocked(displayId))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 return true;
3167 }
3168 }
3169 return false;
3170}
3171
chaviw98318de2021-05-19 16:45:23 -05003172bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003173 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003174 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3175 const WindowInfo* windowInfo = windowHandle->getInfo();
3176 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003177 if (windowHandle == otherHandle) {
3178 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003179 }
chaviw98318de2021-05-19 16:45:23 -05003180 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003181 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003182 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003183 return true;
3184 }
3185 }
3186 return false;
3187}
3188
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003189std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003190 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003191 if (applicationHandle != nullptr) {
3192 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003193 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 } else {
3195 return applicationHandle->getName();
3196 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003197 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003198 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003200 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202}
3203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003205 if (!isUserActivityEvent(eventEntry)) {
3206 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003207 return;
3208 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003209
3210 const int32_t eventType = getUserActivityEventType(eventEntry);
3211 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3212 // Note that we're directly getting the time diff between the current event and the previous
3213 // event. This is assuming that the first user event always happens at a timestamp that is
3214 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3215 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3216 // value than the potential first user activity event time, so this is ok.
3217 std::chrono::nanoseconds timeSinceLastEvent =
3218 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3219 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3220 return;
3221 }
3222 }
3223
Tiger Huang721e26f2018-07-24 22:26:19 +08003224 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003225 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003226 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003227 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003228 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003229 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003230 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 }
3233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003234 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003235 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003236 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3237 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 return;
3239 }
Josep del Riob3981622023-04-18 15:49:45 +00003240 if (windowDisablingUserActivityInfo != nullptr) {
3241 if (DEBUG_DISPATCH_CYCLE) {
3242 ALOGD("Not poking user activity: disabled by window '%s'.",
3243 windowDisablingUserActivityInfo->name.c_str());
3244 }
3245 return;
3246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003249 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003250 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3251 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 return;
3253 }
Josep del Riob3981622023-04-18 15:49:45 +00003254 // If the key code is unknown, we don't consider it user activity
3255 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3256 return;
3257 }
3258 // Don't inhibit events that were intercepted or are not passed to
3259 // the apps, like system shortcuts
3260 if (windowDisablingUserActivityInfo != nullptr &&
3261 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3262 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3263 if (DEBUG_DISPATCH_CYCLE) {
3264 ALOGD("Not poking user activity: disabled by window '%s'.",
3265 windowDisablingUserActivityInfo->name.c_str());
3266 }
3267 return;
3268 }
3269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003272 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003273 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003274 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003275 break;
3276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003279 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003280 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3281 REQUIRES(mLock) {
3282 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003283 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003284 };
3285 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003289 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003290 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003291 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003292 ATRACE_NAME_IF(ATRACE_ENABLED(),
3293 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3294 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003295 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003297 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003298 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003299 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003300 inputTarget.getPointerInfoString().c_str());
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302
3303 // Skip this event if the connection status is not normal.
3304 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003305 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003306 if (DEBUG_DISPATCH_CYCLE) {
3307 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003308 connection->getInputChannelName().c_str(),
3309 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 return;
3312 }
3313
3314 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003316 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003317 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003318 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003320 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003321 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003322 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3323 logDispatchStateLocked();
3324 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3325 "target on connection "
3326 << connection->getInputChannelName() << " for "
3327 << originalMotionEntry.getDescription();
3328 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003330 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003331 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 if (!splitMotionEntry) {
3333 return; // split event was dropped
3334 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003335 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3336 std::string reason = std::string("reason=pointer cancel on split window");
3337 android_log_event_list(LOGTAG_INPUT_CANCEL)
3338 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3339 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003340 if (DEBUG_FOCUS) {
3341 ALOGD("channel '%s' ~ Split motion event.",
3342 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003343 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003344 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003345 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3346 std::move(splitMotionEntry),
3347 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 return;
3349 }
3350 }
3351
3352 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003353 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3354 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355}
3356
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003357void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3358 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3359 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003360 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003361 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3362 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003363 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003364
hongzuo liu95785e22022-09-06 02:51:35 +00003365 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003367 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
3369 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003370 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 startDispatchCycleLocked(currentTime, connection);
3372 }
3373}
3374
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003375void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003376 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003377 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003378 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3379 eventEntry->type == EventEntry::Type::MOTION;
3380 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3381 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3382 << inputTarget << " connection: " << connection->getInputChannelName()
3383 << " entry: " << eventEntry->getDescription();
3384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 // This is a new event.
3386 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003387 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003388 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3389 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003391 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3392 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003393 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003395 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003396 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003397 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3398 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003399 LOG(WARNING) << "channel " << connection->getInputChannelName()
3400 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 return; // skip the inconsistent event
3402 }
3403 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003406 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003407 std::shared_ptr<const MotionEntry> resolvedMotion =
3408 std::static_pointer_cast<const MotionEntry>(eventEntry);
3409 {
3410 // Determine the resolved motion entry.
3411 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3412 int32_t resolvedAction = motionEntry.action;
3413 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003415 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003416 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003417 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003418 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003419 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003420 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003421 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003422 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003423 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003424 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3425 }
3426 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3427 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3428 motionEntry.displayId)) {
3429 if (DEBUG_DISPATCH_CYCLE) {
3430 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3431 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3432 "enter event";
3433 }
3434 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3435 }
3436
3437 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3438 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3439 }
3440 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3441 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3442 }
3443 if (dispatchEntry->targetFlags.test(
3444 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3445 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3446 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003447 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3448 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3449 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003450
3451 dispatchEntry->resolvedFlags = resolvedFlags;
3452 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003453 std::optional<std::vector<PointerProperties>> usingProperties;
3454 std::optional<std::vector<PointerCoords>> usingCoords;
3455 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3456 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3457 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3458 // the dispatcher, and therefore the coordinates of this event are currently
3459 // incorrect. These events should use the coordinates of the last dispatched
3460 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3461 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3462 std::optional<std::pair<std::vector<PointerProperties>,
3463 std::vector<PointerCoords>>>
3464 pointerInfo =
3465 connection->inputState.getPointersOfLastEvent(motionEntry,
3466 hovering);
3467 if (pointerInfo) {
3468 usingProperties = pointerInfo->first;
3469 usingCoords = pointerInfo->second;
3470 }
3471 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003472 // Generate a new MotionEntry with a new eventId using the resolved action and
3473 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003474 resolvedMotion = std::make_shared<
3475 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3476 motionEntry.eventTime, motionEntry.deviceId,
3477 motionEntry.source, motionEntry.displayId,
3478 motionEntry.policyFlags, resolvedAction,
3479 motionEntry.actionButton, resolvedFlags,
3480 motionEntry.metaState, motionEntry.buttonState,
3481 motionEntry.classification, motionEntry.edgeFlags,
3482 motionEntry.xPrecision, motionEntry.yPrecision,
3483 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3484 motionEntry.downTime,
3485 usingProperties.value_or(motionEntry.pointerProperties),
3486 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003487 if (ATRACE_ENABLED()) {
3488 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3489 ") to MotionEvent(id=0x%" PRIx32 ").",
3490 motionEntry.id, resolvedMotion->id);
3491 ATRACE_NAME(message.c_str());
3492 }
3493
3494 // Set the resolved motion entry in the DispatchEntry.
3495 dispatchEntry->eventEntry = resolvedMotion;
3496 eventEntry = resolvedMotion;
3497 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003500 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3501 // devices being active at the same time in the same window, so if a new device is
3502 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003503 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003504 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003505 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003506 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003507 << connection->getInputChannelName() << " with event "
3508 << cancelEvent->getDescription();
3509 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003510 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003511 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003512
3513 // Send these cancel events to the queue before sending the event from the new
3514 // device.
3515 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3516 }
3517
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003518 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003520 LOG(WARNING) << "channel " << connection->getInputChannelName()
3521 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 return; // skip the inconsistent event
3523 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003524 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003525 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003526 // Skip reporting pointer down outside focus to the policy.
3527 break;
3528 }
3529
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003530 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003531 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003532
3533 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003535 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003536 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003537 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3538 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003539 break;
3540 }
Chris Yef59a2f42020-10-16 12:55:26 -07003541 case EventEntry::Type::SENSOR: {
3542 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3543 break;
3544 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003545 case EventEntry::Type::CONFIGURATION_CHANGED:
3546 case EventEntry::Type::DEVICE_RESET: {
3547 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003548 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003549 break;
3550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552
3553 // Remember that we are waiting for this dispatch to complete.
3554 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003555 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557
3558 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003559 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003560 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003561}
3562
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003563/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003564 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003565 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003566 * The first role is to log input interaction with windows, which helps determine what the user was
3567 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3568 * that user started interacting with launcher window, as well as any other window that received
3569 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3570 * when the set of tokens that received the event changes. It is not logged again as long as the
3571 * user is interacting with the same windows.
3572 *
3573 * The second role is to track input device activity for metrics collection. For each input event,
3574 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3575 * input_interaction logs, the device interaction is reported even when the set of interaction
3576 * tokens do not change.
3577 *
3578 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3579 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003581void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3582 const std::vector<InputTarget>& targets) {
3583 int32_t deviceId;
3584 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003585 // Skip ACTION_UP events, and all events other than keys and motions
3586 if (entry.type == EventEntry::Type::KEY) {
3587 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3588 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3589 return;
3590 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003591 deviceId = keyEntry.deviceId;
3592 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 } else if (entry.type == EventEntry::Type::MOTION) {
3594 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3595 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003596 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3597 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003598 return;
3599 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003600 deviceId = motionEntry.deviceId;
3601 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003602 } else {
3603 return; // Not a key or a motion
3604 }
3605
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003606 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003607 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003608 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003609 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003610 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003611 continue; // Skip windows that receive ACTION_OUTSIDE
3612 }
3613
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003614 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003615 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003616 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003617 if (target.windowHandle) {
3618 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3619 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003620 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003621
3622 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3623 REQUIRES(mLock) {
3624 scoped_unlock unlock(mLock);
3625 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3626 };
3627 postCommandLocked(std::move(command));
3628
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003629 if (newConnectionTokens == mInteractionConnectionTokens) {
3630 return; // no change
3631 }
3632 mInteractionConnectionTokens = newConnectionTokens;
3633
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003634 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003635 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003636 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003637 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003638 std::string message = "Interaction with: " + targetList;
3639 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003640 message += "<none>";
3641 }
3642 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3643}
3644
chaviwfd6d3512019-03-25 13:23:49 -07003645void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003646 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003647 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003648 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3649 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003650 return;
3651 }
3652
Vishnu Nairc519ff72021-01-21 08:23:08 -08003653 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003654 if (focusedToken == token) {
3655 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003656 return;
3657 }
3658
Prabir Pradhancef936d2021-07-21 16:17:52 +00003659 auto command = [this, token]() REQUIRES(mLock) {
3660 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003661 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003662 };
3663 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664}
3665
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003666status_t InputDispatcher::publishMotionEvent(Connection& connection,
3667 DispatchEntry& dispatchEntry) const {
3668 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3669 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3670
3671 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003672 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003673
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003674 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003675 // Set the X and Y offset and X and Y scale depending on the input source.
3676 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003677 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003678 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3679 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003680 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003681 scaledCoords[i] = motionEntry.pointerCoords[i];
3682 // Don't apply window scale here since we don't want scale to affect raw
3683 // coordinates. The scale will be sent back to the client and applied
3684 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003685 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003686 }
3687 usingCoords = scaledCoords;
3688 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003689 }
3690
3691 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3692
3693 // Publish the motion event.
3694 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003695 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3696 motionEntry.source, motionEntry.displayId, std::move(hmac),
3697 motionEntry.action, motionEntry.actionButton,
3698 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3699 motionEntry.metaState, motionEntry.buttonState,
3700 motionEntry.classification, dispatchEntry.transform,
3701 motionEntry.xPrecision, motionEntry.yPrecision,
3702 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3703 dispatchEntry.rawTransform, motionEntry.downTime,
3704 motionEntry.eventTime, motionEntry.getPointerCount(),
3705 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003706}
3707
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003709 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003710 ATRACE_NAME_IF(ATRACE_ENABLED(),
3711 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3712 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003713 if (DEBUG_DISPATCH_CYCLE) {
3714 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003717 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003718 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003720 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003721 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722
3723 // Publish the event.
3724 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3726 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003727 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3729 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003731 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3732 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003736 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003737 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3738 keyEntry.deviceId, keyEntry.source,
3739 keyEntry.displayId, std::move(hmac),
3740 keyEntry.action, dispatchEntry->resolvedFlags,
3741 keyEntry.keyCode, keyEntry.scanCode,
3742 keyEntry.metaState, keyEntry.repeatCount,
3743 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003744 if (mTracer) {
3745 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003750 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003751 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003752 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3753 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003754 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003755 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003756 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003757 if (mTracer) {
3758 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3759 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 break;
3761 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003762
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003763 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003765 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003766 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003767 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003768 break;
3769 }
3770
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003771 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3772 const TouchModeEntry& touchModeEntry =
3773 static_cast<const TouchModeEntry&>(eventEntry);
3774 status = connection->inputPublisher
3775 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3776 touchModeEntry.inTouchMode);
3777
3778 break;
3779 }
3780
Prabir Pradhan99987712020-11-10 18:43:05 -08003781 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3782 const auto& captureEntry =
3783 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3784 status = connection->inputPublisher
3785 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003786 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003787 break;
3788 }
3789
arthurhungb89ccb02020-12-30 16:19:01 +08003790 case EventEntry::Type::DRAG: {
3791 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3792 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3793 dragEntry.id, dragEntry.x,
3794 dragEntry.y,
3795 dragEntry.isExiting);
3796 break;
3797 }
3798
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003799 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003800 case EventEntry::Type::DEVICE_RESET:
3801 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003802 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003803 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807
3808 // Check the result.
3809 if (status) {
3810 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003811 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 "This is unexpected because the wait queue is empty, so the pipe "
3814 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003815 "event to it, status=%s(%d)",
3816 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3817 status);
Harry Cutts33476232023-01-30 19:57:29 +00003818 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 } else {
3820 // Pipe is full and we are waiting for the app to finish process some events
3821 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003822 if (DEBUG_DISPATCH_CYCLE) {
3823 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3824 "waiting for the application to catch up",
3825 connection->getInputChannelName().c_str());
3826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828 } else {
3829 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003830 "status=%s(%d)",
3831 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3832 status);
Harry Cutts33476232023-01-30 19:57:29 +00003833 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 return;
3836 }
3837
3838 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003839 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3840 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3841 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003842 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003843 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003844 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003845 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003846 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848}
3849
chaviw09c8d2d2020-08-24 15:48:26 -07003850std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3851 size_t size;
3852 switch (event.type) {
3853 case VerifiedInputEvent::Type::KEY: {
3854 size = sizeof(VerifiedKeyEvent);
3855 break;
3856 }
3857 case VerifiedInputEvent::Type::MOTION: {
3858 size = sizeof(VerifiedMotionEvent);
3859 break;
3860 }
3861 }
3862 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3863 return mHmacKeyManager.sign(start, size);
3864}
3865
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003866const std::array<uint8_t, 32> InputDispatcher::getSignature(
3867 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003868 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003869 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003870 // Only sign events up and down events as the purely move events
3871 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003872 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003873 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003874
3875 VerifiedMotionEvent verifiedEvent =
3876 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3877 verifiedEvent.actionMasked = actionMasked;
3878 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3879 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003880}
3881
3882const std::array<uint8_t, 32> InputDispatcher::getSignature(
3883 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3884 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3885 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003886 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003887}
3888
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003890 const std::shared_ptr<Connection>& connection,
3891 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003892 if (DEBUG_DISPATCH_CYCLE) {
3893 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3894 connection->getInputChannelName().c_str(), seq, toString(handled));
3895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003897 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 return;
3899 }
3900
3901 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003902 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3903 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3904 };
3905 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906}
3907
3908void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003909 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003910 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003911 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003912 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3913 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
3916 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003917 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003918 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003919 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003920 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
3922 // The connection appears to be unrecoverably broken.
3923 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003924 if (connection->status == Connection::Status::NORMAL) {
3925 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
3927 if (notify) {
3928 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003929 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3930 connection->getInputChannelName().c_str());
3931
3932 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003933 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003934 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003935 };
3936 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
3938 }
3939}
3940
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003941void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003942 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003943 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003944 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
3946}
3947
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003948void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003950 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952}
3953
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003954int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3955 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003956 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003957 if (connection == nullptr) {
3958 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3959 connectionToken.get(), events);
3960 return 0; // remove the callback
3961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003963 bool notify;
3964 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3965 if (!(events & ALOOPER_EVENT_INPUT)) {
3966 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3967 "events=0x%x",
3968 connection->getInputChannelName().c_str(), events);
3969 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 }
3971
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003972 nsecs_t currentTime = now();
3973 bool gotOne = false;
3974 status_t status = OK;
3975 for (;;) {
3976 Result<InputPublisher::ConsumerResponse> result =
3977 connection->inputPublisher.receiveConsumerResponse();
3978 if (!result.ok()) {
3979 status = result.error().code();
3980 break;
3981 }
3982
3983 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3984 const InputPublisher::Finished& finish =
3985 std::get<InputPublisher::Finished>(*result);
3986 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3987 finish.consumeTime);
3988 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003989 if (shouldReportMetricsForConnection(*connection)) {
3990 const InputPublisher::Timeline& timeline =
3991 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003992 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3993 connection->getToken(),
3994 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003995 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003996 }
3997 gotOne = true;
3998 }
3999 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00004000 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004001 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 return 1;
4003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 }
4005
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004006 notify = status != DEAD_OBJECT || !connection->monitor;
4007 if (notify) {
4008 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
4009 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
4010 status);
4011 }
4012 } else {
4013 // Monitor channels are never explicitly unregistered.
4014 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004015 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004016 notify = !connection->monitor && stillHaveWindowHandle;
4017 if (notify) {
4018 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4019 connection->getInputChannelName().c_str(), events);
4020 }
4021 }
4022
4023 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004024 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004025 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026}
4027
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004030 // Cancel windows (i.e. non-monitors).
4031 // A channel must have at least one window to receive any input. If a window was removed, the
4032 // event streams directed to the window will already have been canceled during window removal.
4033 // So there is no need to generate cancellations for connections without any windows.
4034 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4035 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4036 // through a non-touched window if there are more than one window for an input channel.
4037 if (cancelPointers) {
4038 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4039 if (options.displayId.has_value() && options.displayId != displayId) {
4040 continue;
4041 }
4042 for (const auto& touchedWindow : touchState.windows) {
4043 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4044 }
4045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004047 // Follow up by generating cancellations for all windows, because we don't explicitly track
4048 // the windows that have an ongoing focus event stream.
4049 if (cancelNonPointers) {
4050 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4051 for (const auto& windowHandle : handles) {
4052 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4053 }
4054 }
4055 }
4056
4057 // Cancel monitors.
4058 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059}
4060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004062 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004063 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004064 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004065 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4066 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004067 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004068 }
4069}
4070
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004071void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4072 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4073 const std::shared_ptr<Connection>& connection) {
4074 if (windowHandle == nullptr) {
4075 LOG(FATAL) << __func__ << ": Window handle must not be null";
4076 }
4077 if (connection) {
4078 // The connection can be optionally provided to avoid multiple lookups.
4079 if (windowHandle->getToken() != connection->getToken()) {
4080 LOG(FATAL) << __func__
4081 << ": Wrong connection provided for window: " << windowHandle->getName();
4082 }
4083 }
4084
4085 std::shared_ptr<Connection> resolvedConnection =
4086 connection ? connection : getConnectionLocked(windowHandle->getToken());
4087 if (!resolvedConnection) {
4088 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4089 return;
4090 }
4091 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4092}
4093
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004095 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4096 const sp<WindowInfoHandle>& window) {
4097 if (!connection->monitor && window == nullptr) {
4098 LOG(FATAL) << __func__
4099 << ": Cannot send event to non-monitor channel without a window - channel: "
4100 << connection->getInputChannelName();
4101 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004102 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 return;
4104 }
4105
4106 nsecs_t currentTime = now();
4107
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004109 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004111 if (cancelationEvents.empty()) {
4112 return;
4113 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004114
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004115 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4116 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004117 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004118 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004119 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004121
Arthur Hungb3307ee2021-10-14 10:57:37 +00004122 std::string reason = std::string("reason=").append(options.reason);
4123 android_log_event_list(LOGTAG_INPUT_CANCEL)
4124 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4125
hongzuo liu95785e22022-09-06 02:51:35 +00004126 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004127 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004128 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004129 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004130
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004131 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004132 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004133 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004134
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004135 switch (cancelationEventEntry->type) {
4136 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004137 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004138 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004139 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4140 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004141 } else {
4142 targets.emplace_back(fallbackTarget);
4143 }
4144 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004147 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004148 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004149 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004150 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004151 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004152 pointerIndex++) {
4153 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4154 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004155 if (mDragState && mDragState->dragWindow->getToken() == token &&
4156 pointerIds.test(mDragState->pointerId)) {
4157 LOG(INFO) << __func__
4158 << ": Canceling drag and drop because the pointers for the drag "
4159 "window are being canceled.";
4160 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4161 mDragState.reset();
4162 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004163 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4164 ftl::Flags<InputTarget::Flags>(), pointerIds,
4165 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004166 } else {
4167 targets.emplace_back(fallbackTarget);
4168 const auto it = mDisplayInfos.find(motionEntry.displayId);
4169 if (it != mDisplayInfos.end()) {
4170 targets.back().displayTransform = it->second.transform;
4171 targets.back().setDefaultPointerTransform(it->second.transform);
4172 }
4173 }
4174 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004177 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004178 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004179 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4180 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004181 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004182 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004183 break;
4184 }
4185 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004186 case EventEntry::Type::DEVICE_RESET:
4187 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004188 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004189 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004190 break;
4191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004194 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004195 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004197
hongzuo liu95785e22022-09-06 02:51:35 +00004198 // If the outbound queue was previously empty, start the dispatch cycle going.
4199 if (wasEmpty && !connection->outboundQueue.empty()) {
4200 startDispatchCycleLocked(currentTime, connection);
4201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202}
4203
Svet Ganov5d3bc372020-01-26 23:11:07 -08004204void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004205 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004206 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004207 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004208 return;
4209 }
4210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004211 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004212 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004213
4214 if (downEvents.empty()) {
4215 return;
4216 }
4217
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004218 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004219 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4220 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004221 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004222
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004223 const auto [_, touchedWindowState, displayId] =
4224 findTouchStateWindowAndDisplayLocked(connection->getToken());
4225 if (touchedWindowState == nullptr) {
4226 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4227 }
4228 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004229
hongzuo liu95785e22022-09-06 02:51:35 +00004230 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004231 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004232 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233 switch (downEventEntry->type) {
4234 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004235 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4236 if (windowHandle != nullptr) {
4237 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004238 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004239 pointerIndex++) {
4240 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4241 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004242 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4243 targetFlags, pointerIds, motionEntry.downTime,
4244 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004245 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004246 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004247 const auto it = mDisplayInfos.find(motionEntry.displayId);
4248 if (it != mDisplayInfos.end()) {
4249 targets.back().displayTransform = it->second.transform;
4250 targets.back().setDefaultPointerTransform(it->second.transform);
4251 }
4252 }
4253 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004254 break;
4255 }
4256
4257 case EventEntry::Type::KEY:
4258 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004259 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004260 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004261 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004262 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004263 case EventEntry::Type::SENSOR:
4264 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004265 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004266 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004267 break;
4268 }
4269 }
4270
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004271 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004272 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004273 }
4274
hongzuo liu95785e22022-09-06 02:51:35 +00004275 // If the outbound queue was previously empty, start the dispatch cycle going.
4276 if (wasEmpty && !connection->outboundQueue.empty()) {
4277 startDispatchCycleLocked(downTime, connection);
4278 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004279}
4280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004282 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4283 nsecs_t splitDownTime) {
4284 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
4286 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004287 std::vector<PointerProperties> splitPointerProperties;
4288 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004290 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 uint32_t splitPointerCount = 0;
4292
4293 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004296 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004298 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004300 splitPointerProperties.push_back(pointerProperties);
4301 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 splitPointerCount += 1;
4303 }
4304 }
4305
4306 if (splitPointerCount != pointerIds.count()) {
4307 // This is bad. We are missing some of the pointers that we expected to deliver.
4308 // Most likely this indicates that we received an ACTION_MOVE events that has
4309 // different pointer ids than we expected based on the previous ACTION_DOWN
4310 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4311 // in this way.
4312 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004313 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004314 "a broken sequence of pointer ids from the input device: %s",
4315 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004316 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
4318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004319 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4322 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004323 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004325 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004327 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 if (pointerIds.count() == 1) {
4329 // The first/last pointer went down/up.
4330 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004332 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4333 ? AMOTION_EVENT_ACTION_CANCEL
4334 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 } else {
4336 // A secondary pointer went down/up.
4337 uint32_t splitPointerIndex = 0;
4338 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4339 splitPointerIndex += 1;
4340 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004341 action = maskedAction |
4342 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344 } else {
4345 // An unrelated pointer changed.
4346 action = AMOTION_EVENT_ACTION_MOVE;
4347 }
4348 }
4349
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004350 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4351 logDispatchStateLocked();
4352 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4353 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4354 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004355 }
4356
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004357 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004358 ATRACE_NAME_IF(ATRACE_ENABLED(),
4359 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4360 ").",
4361 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004362 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004363 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4364 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 originalMotionEntry.deviceId, originalMotionEntry.source,
4366 originalMotionEntry.displayId,
4367 originalMotionEntry.policyFlags, action,
4368 originalMotionEntry.actionButton,
4369 originalMotionEntry.flags, originalMotionEntry.metaState,
4370 originalMotionEntry.buttonState,
4371 originalMotionEntry.classification,
4372 originalMotionEntry.edgeFlags,
4373 originalMotionEntry.xPrecision,
4374 originalMotionEntry.yPrecision,
4375 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004376 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004377 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 return splitMotionEntry;
4380}
4381
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004382void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4383 std::scoped_lock _l(mLock);
4384 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4385}
4386
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004387void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004388 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004389 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
Antonio Kantekf16f2832021-09-28 04:39:20 +00004392 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004394 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004398 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 } // release lock
4400
4401 if (needWake) {
4402 mLooper->wake();
4403 }
4404}
4405
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004406void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004407 ALOGD_IF(debugInboundEventDetails(),
4408 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4409 ", deviceId=%d, source=%s, displayId=%" PRId32
4410 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4411 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004412 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4413 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4414 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004415 Result<void> keyCheck = validateKeyEvent(args.action);
4416 if (!keyCheck.ok()) {
4417 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 return;
4419 }
4420
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004421 uint32_t policyFlags = args.policyFlags;
4422 int32_t flags = args.flags;
4423 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004424 // InputDispatcher tracks and generates key repeats on behalf of
4425 // whatever notifies it, so repeatCount should always be set to 0
4426 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4428 policyFlags |= POLICY_FLAG_VIRTUAL;
4429 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 if (policyFlags & POLICY_FLAG_FUNCTION) {
4432 metaState |= AMETA_FUNCTION_ON;
4433 }
4434
4435 policyFlags |= POLICY_FLAG_TRUSTED;
4436
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004437 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4440 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4441 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442
Michael Wright2b3c3302018-03-02 17:19:13 +00004443 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004444 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004445 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4446 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004447 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449
Antonio Kantekf16f2832021-09-28 04:39:20 +00004450 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 { // acquire lock
4452 mLock.lock();
4453
4454 if (shouldSendKeyToInputFilterLocked(args)) {
4455 mLock.unlock();
4456
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004457 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004458 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 return; // event was consumed by the filter
4460 }
4461
4462 mLock.lock();
4463 }
4464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004465 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004466 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4467 args.deviceId, args.source, args.displayId, policyFlags,
4468 args.action, flags, keyCode, args.scanCode, metaState,
4469 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004470 if (mTracer) {
4471 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 mLock.unlock();
4476 } // release lock
4477
4478 if (needWake) {
4479 mLooper->wake();
4480 }
4481}
4482
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 return mInputFilterEnabled;
4485}
4486
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004488 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004489 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004491 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4493 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4495 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4496 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4497 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4498 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004499 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004500 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4501 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004502 i, args.pointerProperties[i].id,
4503 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4504 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4505 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4506 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4507 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4508 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4509 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4510 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4511 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4512 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004515
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004516 Result<void> motionCheck =
4517 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4518 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004519 if (!motionCheck.ok()) {
4520 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4521 return;
4522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004524 if (DEBUG_VERIFY_EVENTS) {
4525 auto [it, _] =
4526 mVerifiersByDisplay.try_emplace(args.displayId,
4527 StringPrintf("display %" PRId32, args.displayId));
4528 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004529 it->second.processMovement(args.deviceId, args.source, args.action,
4530 args.getPointerCount(), args.pointerProperties.data(),
4531 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004532 if (!result.ok()) {
4533 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4534 }
4535 }
4536
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004537 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004539
4540 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004541 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4542 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004543 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4544 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004545 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Antonio Kantekf16f2832021-09-28 04:39:20 +00004548 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 { // acquire lock
4550 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004551 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4552 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4553 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004554 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004555 if (touchStateIt != mTouchStatesByDisplay.end()) {
4556 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004557 if (touchState.hasTouchingPointers(args.deviceId) ||
4558 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004559 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4560 }
4561 }
4562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
4564 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004565 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004566 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004567 displayTransform = it->second.transform;
4568 }
4569
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 mLock.unlock();
4571
4572 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004573 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4574 args.action, args.actionButton, args.flags, args.edgeFlags,
4575 args.metaState, args.buttonState, args.classification,
4576 displayTransform, args.xPrecision, args.yPrecision,
4577 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004578 args.downTime, args.eventTime, args.getPointerCount(),
4579 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580
4581 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004582 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 return; // event was consumed by the filter
4584 }
4585
4586 mLock.lock();
4587 }
4588
4589 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004590 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004591 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4592 args.deviceId, args.source, args.displayId,
4593 policyFlags, args.action, args.actionButton,
4594 args.flags, args.metaState, args.buttonState,
4595 args.classification, args.edgeFlags, args.xPrecision,
4596 args.yPrecision, args.xCursorPosition,
4597 args.yCursorPosition, args.downTime,
4598 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004599 if (mTracer) {
4600 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004603 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4604 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004605 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004606 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004607 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4608 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4609 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004610 }
4611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004612 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 mLock.unlock();
4614 } // release lock
4615
4616 if (needWake) {
4617 mLooper->wake();
4618 }
4619}
4620
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004621void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004622 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004623 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4624 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004625 args.id, args.eventTime, args.deviceId, args.source,
4626 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004627 }
Chris Yef59a2f42020-10-16 12:55:26 -07004628
Antonio Kantekf16f2832021-09-28 04:39:20 +00004629 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004630 { // acquire lock
4631 mLock.lock();
4632
4633 // Just enqueue a new sensor event.
4634 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4636 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4637 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004638
4639 needWake = enqueueInboundEventLocked(std::move(newEntry));
4640 mLock.unlock();
4641 } // release lock
4642
4643 if (needWake) {
4644 mLooper->wake();
4645 }
4646}
4647
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004648void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004649 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4651 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004653 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004654}
4655
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004657 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658}
4659
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004660void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004661 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004662 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4663 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004664 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004667 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004669 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670}
4671
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004672void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004673 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004674 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4675 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677
Antonio Kantekf16f2832021-09-28 04:39:20 +00004678 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004680 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004682 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004683 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004684 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004685
4686 for (auto& [_, verifier] : mVerifiersByDisplay) {
4687 verifier.resetDevice(args.deviceId);
4688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 } // release lock
4690
4691 if (needWake) {
4692 mLooper->wake();
4693 }
4694}
4695
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004696void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004697 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004698 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4699 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004700 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004701
Antonio Kantekf16f2832021-09-28 04:39:20 +00004702 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004703 { // acquire lock
4704 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004705 auto entry =
4706 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004707 needWake = enqueueInboundEventLocked(std::move(entry));
4708 } // release lock
4709
4710 if (needWake) {
4711 mLooper->wake();
4712 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004713}
4714
Prabir Pradhan5735a322022-04-11 17:23:34 +00004715InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004716 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004717 InputEventInjectionSync syncMode,
4718 std::chrono::milliseconds timeout,
4719 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004720 Result<void> eventValidation = validateInputEvent(*event);
4721 if (!eventValidation.ok()) {
4722 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4723 return InputEventInjectionResult::FAILED;
4724 }
4725
Prabir Pradhan65613802023-02-22 23:36:58 +00004726 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004727 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4728 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4729 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4730 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004731 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004732 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
Prabir Pradhan5735a322022-04-11 17:23:34 +00004734 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004736 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004737 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4738 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4739 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4740 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4741 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004742 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004743 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004744 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004745 }
4746
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004747 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4748 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4749
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004750 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004752 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004753 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004754 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004755 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004756 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4757 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4758 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004759 int32_t keyCode = incomingKey.getKeyCode();
4760 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004761 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004762 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004763 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4764 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4765 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4768 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004769 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004770
4771 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4772 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004773 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004774 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4775 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4776 std::to_string(t.duration().count()).c_str());
4777 }
4778 }
4779
4780 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004782 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4783 incomingKey.getEventTime(), resolvedDeviceId,
4784 incomingKey.getSource(), incomingKey.getDisplayId(),
4785 policyFlags, action, flags, keyCode,
4786 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004787 incomingKey.getRepeatCount(),
4788 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004789 if (mTracer) {
4790 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4791 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004792 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004793 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 }
4795
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004796 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004797 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004798 const bool isPointerEvent =
4799 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4800 // If a pointer event has no displayId specified, inject it to the default display.
4801 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4802 ? ADISPLAY_ID_DEFAULT
4803 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004804 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805
4806 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004807 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004809 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4810 motionEvent.getAction(), eventTime,
4811 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4813 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4814 std::to_string(t.duration().count()).c_str());
4815 }
4816 }
4817
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004818 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4819 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4820 }
4821
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004823 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004824 const size_t pointerCount = motionEvent.getPointerCount();
4825 const std::vector<PointerProperties>
4826 pointerProperties(motionEvent.getPointerProperties(),
4827 motionEvent.getPointerProperties() + pointerCount);
4828
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004829 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004830 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004831 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4832 *sampleEventTimes, resolvedDeviceId,
4833 motionEvent.getSource(), displayId, policyFlags,
4834 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004835 motionEvent.getActionButton(), flags,
4836 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004837 motionEvent.getButtonState(),
4838 motionEvent.getClassification(),
4839 motionEvent.getEdgeFlags(),
4840 motionEvent.getXPrecision(),
4841 motionEvent.getYPrecision(),
4842 motionEvent.getRawXCursorPosition(),
4843 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004844 motionEvent.getDownTime(), pointerProperties,
4845 std::vector<PointerCoords>(samplePointerCoords,
4846 samplePointerCoords +
4847 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004848 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004849 if (mTracer) {
4850 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4851 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004852 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004853 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004854 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004855 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004856 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004857 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4858 resolvedDeviceId, motionEvent.getSource(), displayId,
4859 policyFlags, motionEvent.getAction(),
4860 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004861 motionEvent.getMetaState(), motionEvent.getButtonState(),
4862 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4863 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4864 motionEvent.getRawXCursorPosition(),
4865 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4866 pointerProperties,
4867 std::vector<PointerCoords>(samplePointerCoords,
4868 samplePointerCoords +
4869 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004870 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4871 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004872 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004873 }
4874 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004877 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004878 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004879 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 }
4881
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004883 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004884 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004885 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004887 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004888 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 }
4890
4891 mLock.unlock();
4892
4893 if (needWake) {
4894 mLooper->wake();
4895 }
4896
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004897 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004899 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 if (syncMode == InputEventInjectionSync::NONE) {
4902 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 } else {
4904 for (;;) {
4905 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004906 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 break;
4908 }
4909
4910 nsecs_t remainingTimeout = endTime - now();
4911 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004912 if (DEBUG_INJECTION) {
4913 ALOGD("injectInputEvent - Timed out waiting for injection result "
4914 "to become available.");
4915 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004916 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 break;
4918 }
4919
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004920 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 }
4922
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004923 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4924 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004926 if (DEBUG_INJECTION) {
4927 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4928 injectionState->pendingForegroundDispatches);
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 nsecs_t remainingTimeout = endTime - now();
4931 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004932 if (DEBUG_INJECTION) {
4933 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4934 "dispatches to finish.");
4935 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004936 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937 break;
4938 }
4939
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004940 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 }
4942 }
4943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 } // release lock
4945
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004946 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004947 LOG(INFO) << "injectInputEvent - Finished with result "
4948 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950
4951 return injectionResult;
4952}
4953
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004954std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004955 std::array<uint8_t, 32> calculatedHmac;
4956 std::unique_ptr<VerifiedInputEvent> result;
4957 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004958 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004959 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4960 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4961 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004962 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004963 break;
4964 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004965 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004966 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4967 VerifiedMotionEvent verifiedMotionEvent =
4968 verifiedMotionEventFromMotionEvent(motionEvent);
4969 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004970 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004971 break;
4972 }
4973 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004974 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004975 return nullptr;
4976 }
4977 }
4978 if (calculatedHmac == INVALID_HMAC) {
4979 return nullptr;
4980 }
tyiu1573a672023-02-21 22:38:32 +00004981 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004982 return nullptr;
4983 }
4984 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004985}
4986
Prabir Pradhan24047542023-11-02 17:14:59 +00004987void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004988 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004989 if (!entry.injectionState) {
4990 // Not an injected event.
4991 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004993
4994 InjectionState& injectionState = *entry.injectionState;
4995 if (DEBUG_INJECTION) {
4996 LOG(INFO) << "Setting input event injection result to "
4997 << ftl::enum_string(injectionResult);
4998 }
4999
5000 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
5001 // Log the outcome since the injector did not wait for the injection result.
5002 switch (injectionResult) {
5003 case InputEventInjectionResult::SUCCEEDED:
5004 ALOGV("Asynchronous input event injection succeeded.");
5005 break;
5006 case InputEventInjectionResult::TARGET_MISMATCH:
5007 ALOGV("Asynchronous input event injection target mismatch.");
5008 break;
5009 case InputEventInjectionResult::FAILED:
5010 ALOGW("Asynchronous input event injection failed.");
5011 break;
5012 case InputEventInjectionResult::TIMED_OUT:
5013 ALOGW("Asynchronous input event injection timed out.");
5014 break;
5015 case InputEventInjectionResult::PENDING:
5016 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5017 break;
5018 }
5019 }
5020
5021 injectionState.injectionResult = injectionResult;
5022 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023}
5024
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005025void InputDispatcher::transformMotionEntryForInjectionLocked(
5026 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005027 // Input injection works in the logical display coordinate space, but the input pipeline works
5028 // display space, so we need to transform the injected events accordingly.
5029 const auto it = mDisplayInfos.find(entry.displayId);
5030 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005031 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005032
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005033 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5034 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5035 const vec2 cursor =
5036 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5037 {entry.xCursorPosition, entry.yCursorPosition});
5038 entry.xCursorPosition = cursor.x;
5039 entry.yCursorPosition = cursor.y;
5040 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005041 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005042 entry.pointerCoords[i] =
5043 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5044 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005045 }
5046}
5047
Prabir Pradhan24047542023-11-02 17:14:59 +00005048void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005049 if (entry.injectionState) {
5050 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
5052}
5053
Prabir Pradhan24047542023-11-02 17:14:59 +00005054void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005055 if (entry.injectionState) {
5056 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005058 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005059 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061 }
5062}
5063
chaviw98318de2021-05-19 16:45:23 -05005064const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005065 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005066 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005067 auto it = mWindowHandlesByDisplay.find(displayId);
5068 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005069}
5070
chaviw98318de2021-05-19 16:45:23 -05005071sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005072 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005073 if (windowHandleToken == nullptr) {
5074 return nullptr;
5075 }
5076
Prabir Pradhan16463382023-10-12 23:03:19 +00005077 if (!displayId) {
5078 // Look through all displays.
5079 for (auto& it : mWindowHandlesByDisplay) {
5080 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5081 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5082 if (windowHandle->getToken() == windowHandleToken) {
5083 return windowHandle;
5084 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005087 return nullptr;
5088 }
5089
Prabir Pradhan16463382023-10-12 23:03:19 +00005090 // Only look through the requested display.
5091 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005092 if (windowHandle->getToken() == windowHandleToken) {
5093 return windowHandle;
5094 }
5095 }
5096 return nullptr;
5097}
5098
chaviw98318de2021-05-19 16:45:23 -05005099sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5100 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005101 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005102 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5103 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005104 if (handle->getId() == windowHandle->getId() &&
5105 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005106 if (windowHandle->getInfo()->displayId != it.first) {
5107 ALOGE("Found window %s in display %" PRId32
5108 ", but it should belong to display %" PRId32,
5109 windowHandle->getName().c_str(), it.first,
5110 windowHandle->getInfo()->displayId);
5111 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005112 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 }
5115 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005116 return nullptr;
5117}
5118
chaviw98318de2021-05-19 16:45:23 -05005119sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005120 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5121 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122}
5123
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005124ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5125 auto displayInfoIt = mDisplayInfos.find(displayId);
5126 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5127 : kIdentityTransform;
5128}
5129
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005130bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5131 const MotionEntry& motionEntry) const {
5132 const WindowInfo& info = *window->getInfo();
5133
5134 // Skip spy window targets that are not valid for targeted injection.
5135 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005136 return false;
5137 }
5138
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005139 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5140 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5141 return false;
5142 }
5143
5144 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5145 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5146 window->getName().c_str());
5147 return false;
5148 }
5149
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005150 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005151 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005152 ALOGW("Not sending touch to %s because there's no corresponding connection",
5153 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005154 return false;
5155 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005156
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005157 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005158 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005159 return false;
5160 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005161
5162 // Drop events that can't be trusted due to occlusion
5163 const auto [x, y] = resolveTouchedPosition(motionEntry);
5164 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5165 if (!isTouchTrustedLocked(occlusionInfo)) {
5166 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005167 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005168 for (const auto& log : occlusionInfo.debugInfo) {
5169 ALOGD("%s", log.c_str());
5170 }
5171 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005172 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5173 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005174 return false;
5175 }
5176
5177 // Drop touch events if requested by input feature
5178 if (shouldDropInput(motionEntry, window)) {
5179 return false;
5180 }
5181
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005182 // Ignore touches if stylus is down anywhere on screen
5183 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5184 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5185 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5186 return false;
5187 }
5188
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005189 return true;
5190}
5191
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005192void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005193 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5194 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005195 // Remove all handles on a display if there are no windows left.
5196 mWindowHandlesByDisplay.erase(displayId);
5197 return;
5198 }
5199
5200 // Since we compare the pointer of input window handles across window updates, we need
5201 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005202 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5203 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5204 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005205 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005206 }
5207
chaviw98318de2021-05-19 16:45:23 -05005208 std::vector<sp<WindowInfoHandle>> newHandles;
5209 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005210 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005211 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005212 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005213 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005214 const bool canReceiveInput =
5215 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5216 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005217 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005218 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005219 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005220 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005221 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005222 }
5223
5224 if (info->displayId != displayId) {
5225 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5226 handle->getName().c_str(), displayId, info->displayId);
5227 continue;
5228 }
5229
Robert Carredd13602020-04-13 17:24:34 -07005230 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5231 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005232 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005233 oldHandle->updateFrom(handle);
5234 newHandles.push_back(oldHandle);
5235 } else {
5236 newHandles.push_back(handle);
5237 }
5238 }
5239
5240 // Insert or replace
5241 mWindowHandlesByDisplay[displayId] = newHandles;
5242}
5243
Arthur Hungb92218b2018-08-14 12:00:21 +08005244/**
5245 * Called from InputManagerService, update window handle list by displayId that can receive input.
5246 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5247 * If set an empty list, remove all handles from the specific display.
5248 * For focused handle, check if need to change and send a cancel event to previous one.
5249 * For removed handle, check if need to send a cancel event if already in touch.
5250 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005251void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005252 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005253 if (DEBUG_FOCUS) {
5254 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005255 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005256 windowList += iwh->getName() + " ";
5257 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005258 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260
Prabir Pradhand65552b2021-10-07 11:23:50 -07005261 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005262 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005263 const WindowInfo& info = *window->getInfo();
5264
5265 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005266 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005267 if (noInputWindow && window->getToken() != nullptr) {
5268 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5269 window->getName().c_str());
5270 window->releaseChannel();
5271 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005272
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005273 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005274 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5275 !info.inputConfig.test(
5276 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005277 "%s has feature SPY, but is not a trusted overlay.",
5278 window->getName().c_str());
5279
Prabir Pradhand65552b2021-10-07 11:23:50 -07005280 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005281 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5282 !info.inputConfig.test(
5283 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005284 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5285 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005286 }
5287
Arthur Hung72d8dc32020-03-28 00:48:39 +00005288 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005289 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005290 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291
chaviw98318de2021-05-19 16:45:23 -05005292 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005293
chaviw98318de2021-05-19 16:45:23 -05005294 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005295
Vishnu Nairc519ff72021-01-21 08:23:08 -08005296 std::optional<FocusResolver::FocusChanges> changes =
5297 mFocusResolver.setInputWindows(displayId, windowHandles);
5298 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005299 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005302 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5303 mTouchStatesByDisplay.find(displayId);
5304 if (stateIt != mTouchStatesByDisplay.end()) {
5305 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005306 for (size_t i = 0; i < state.windows.size();) {
5307 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005308 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005309 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5310 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005311 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5312 "touched window was removed");
5313 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5314 // Since we are about to drop the touch, cancel the events for the wallpaper as
5315 // well.
5316 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5317 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5318 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5319 if (const auto& ww = state.getWallpaperWindow(); ww) {
5320 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005323 state.windows.erase(state.windows.begin() + i);
5324 } else {
5325 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327 }
arthurhungb89ccb02020-12-30 16:19:01 +08005328
arthurhung6d4bed92021-03-17 11:59:33 +08005329 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005330 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005331 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005332 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005333 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005334 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5335 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005336 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005337 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005338 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005339
Arthur Hung72d8dc32020-03-28 00:48:39 +00005340 // Release information for windows that are no longer present.
5341 // This ensures that unused input channels are released promptly.
5342 // Otherwise, they might stick around until the window handle is destroyed
5343 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005344 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005345 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005346 if (DEBUG_FOCUS) {
5347 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005348 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005349 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005350 }
chaviw291d88a2019-02-14 10:33:58 -08005351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352}
5353
5354void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005355 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005356 if (DEBUG_FOCUS) {
5357 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5358 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5359 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005360 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005361 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005362 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 } // release lock
5364
5365 // Wake up poll loop since it may need to make new input dispatching choices.
5366 mLooper->wake();
5367}
5368
Vishnu Nair599f1412021-06-21 10:39:58 -07005369void InputDispatcher::setFocusedApplicationLocked(
5370 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5371 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5372 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5373
5374 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5375 return; // This application is already focused. No need to wake up or change anything.
5376 }
5377
5378 // Set the new application handle.
5379 if (inputApplicationHandle != nullptr) {
5380 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5381 } else {
5382 mFocusedApplicationHandlesByDisplay.erase(displayId);
5383 }
5384
5385 // No matter what the old focused application was, stop waiting on it because it is
5386 // no longer focused.
5387 resetNoFocusedWindowTimeoutLocked();
5388}
5389
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005390void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5391 if (interval.count() < 0) {
5392 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5393 }
5394 std::scoped_lock _l(mLock);
5395 mMinTimeBetweenUserActivityPokes = interval;
5396}
5397
Tiger Huang721e26f2018-07-24 22:26:19 +08005398/**
5399 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5400 * the display not specified.
5401 *
5402 * We track any unreleased events for each window. If a window loses the ability to receive the
5403 * released event, we will send a cancel event to it. So when the focused display is changed, we
5404 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5405 * display. The display-specified events won't be affected.
5406 */
5407void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005408 if (DEBUG_FOCUS) {
5409 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5410 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005411 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005412 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005413
5414 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005415 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005417 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005418 const auto windowHandle =
5419 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5420 if (windowHandle == nullptr) {
5421 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005422 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005423 CancelationOptions
5424 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5425 "The display which contains this window no longer has focus.");
5426 options.displayId = ADISPLAY_ID_NONE;
5427 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005428 }
5429 mFocusedDisplayId = displayId;
5430
Chris Ye3c2d6f52020-08-09 10:39:48 -07005431 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005432 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005433 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005434
Vishnu Nairad321cd2020-08-20 16:40:21 -07005435 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005436 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005437 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005438 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005439 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005440 }
5441 }
5442 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005443 } // release lock
5444
5445 // Wake up poll loop since it may need to make new input dispatching choices.
5446 mLooper->wake();
5447}
5448
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005450 if (DEBUG_FOCUS) {
5451 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453
5454 bool changed;
5455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005456 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457
5458 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5459 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005460 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 }
5462
5463 if (mDispatchEnabled && !enabled) {
5464 resetAndDropEverythingLocked("dispatcher is being disabled");
5465 }
5466
5467 mDispatchEnabled = enabled;
5468 mDispatchFrozen = frozen;
5469 changed = true;
5470 } else {
5471 changed = false;
5472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 } // release lock
5474
5475 if (changed) {
5476 // Wake up poll loop since it may need to make new input dispatching choices.
5477 mLooper->wake();
5478 }
5479}
5480
5481void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005482 if (DEBUG_FOCUS) {
5483 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
5486 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005487 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
5489 if (mInputFilterEnabled == enabled) {
5490 return;
5491 }
5492
5493 mInputFilterEnabled = enabled;
5494 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5495 } // release lock
5496
5497 // Wake up poll loop since there might be work to do to drop everything.
5498 mLooper->wake();
5499}
5500
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005501bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005502 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005503 bool needWake = false;
5504 {
5505 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005506 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005507 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005508 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005509 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5510 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005511 mTouchModePerDisplay.count(displayId) == 0
5512 ? "not set"
5513 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5514
Antonio Kantek15beb512022-06-13 22:35:41 +00005515 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5516 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005518 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005519 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005520 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5521 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005522 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005523 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005524 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005525 return false;
5526 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005527 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005528 mTouchModePerDisplay[displayId] = inTouchMode;
5529 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5530 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005531 needWake = enqueueInboundEventLocked(std::move(entry));
5532 } // release lock
5533
5534 if (needWake) {
5535 mLooper->wake();
5536 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005537 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005538}
5539
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005540bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005541 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5542 if (focusedToken == nullptr) {
5543 return false;
5544 }
5545 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5546 return isWindowOwnedBy(windowHandle, pid, uid);
5547}
5548
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005549bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005550 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5551 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5552 const sp<WindowInfoHandle> windowHandle =
5553 getWindowHandleLocked(connectionToken);
5554 return isWindowOwnedBy(windowHandle, pid, uid);
5555 }) != mInteractionConnectionTokens.end();
5556}
5557
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005558void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5559 if (opacity < 0 || opacity > 1) {
5560 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5561 return;
5562 }
5563
5564 std::scoped_lock lock(mLock);
5565 mMaximumObscuringOpacityForTouch = opacity;
5566}
5567
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005568std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5569InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5571 for (TouchedWindow& w : state.windows) {
5572 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005573 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005574 }
5575 }
5576 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005577 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005578}
5579
Prabir Pradhan367f3432024-02-13 23:05:58 +00005580bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5581 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005582 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005583 if (DEBUG_FOCUS) {
5584 ALOGD("Trivial transfer to same window.");
5585 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005586 return true;
5587 }
5588
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005590 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591
Arthur Hungabbb9d82021-09-01 14:52:30 +00005592 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005593 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005594
Arthur Hungabbb9d82021-09-01 14:52:30 +00005595 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005596 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 return false;
5598 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005599 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5600 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005601 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5602 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005603 return false;
5604 }
5605 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005606
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005607 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5608 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5609 if (!toWindowHandle) {
5610 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611 return false;
5612 }
5613
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005614 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005615 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005616 touchedWindow->windowHandle->getName().c_str(),
5617 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 }
5619
Arthur Hungabbb9d82021-09-01 14:52:30 +00005620 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005621 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005622 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005623 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624
Arthur Hungabbb9d82021-09-01 14:52:30 +00005625 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005626 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005627 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005628 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005629 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005630 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005631 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005632 // Transferring touch focus using this API should not effect the focused window.
5633 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005634 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005635 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636
Arthur Hungabbb9d82021-09-01 14:52:30 +00005637 // Store the dragging window.
5638 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005639 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005640 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5641 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005642 return false;
5643 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005644 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005645 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005646 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 }
5648
Arthur Hungabbb9d82021-09-01 14:52:30 +00005649 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005650 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5651 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005652 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005653 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005654 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5655 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005656 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005657 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5658 newTargetFlags);
5659
5660 // Check if the wallpaper window should deliver the corresponding event.
5661 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005662 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 } // release lock
5665
5666 // Wake up poll loop since it may need to make new input dispatching choices.
5667 mLooper->wake();
5668 return true;
5669}
5670
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005671/**
5672 * Get the touched foreground window on the given display.
5673 * Return null if there are no windows touched on that display, or if more than one foreground
5674 * window is being touched.
5675 */
5676sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5677 auto stateIt = mTouchStatesByDisplay.find(displayId);
5678 if (stateIt == mTouchStatesByDisplay.end()) {
5679 ALOGI("No touch state on display %" PRId32, displayId);
5680 return nullptr;
5681 }
5682
5683 const TouchState& state = stateIt->second;
5684 sp<WindowInfoHandle> touchedForegroundWindow;
5685 // If multiple foreground windows are touched, return nullptr
5686 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005687 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005688 if (touchedForegroundWindow != nullptr) {
5689 ALOGI("Two or more foreground windows: %s and %s",
5690 touchedForegroundWindow->getName().c_str(),
5691 window.windowHandle->getName().c_str());
5692 return nullptr;
5693 }
5694 touchedForegroundWindow = window.windowHandle;
5695 }
5696 }
5697 return touchedForegroundWindow;
5698}
5699
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005700// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005701bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5702 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005703 sp<IBinder> fromToken;
5704 { // acquire lock
5705 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005706 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005707 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005708 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5709 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005710 return false;
5711 }
5712
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005713 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5714 if (from == nullptr) {
5715 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5716 return false;
5717 }
5718
5719 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005720 } // release lock
5721
Prabir Pradhan367f3432024-02-13 23:05:58 +00005722 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005723}
5724
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005726 if (DEBUG_FOCUS) {
5727 ALOGD("Resetting and dropping all events (%s).", reason);
5728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729
Michael Wrightfb04fd52022-11-24 22:31:11 +00005730 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 synthesizeCancelationEventsForAllConnectionsLocked(options);
5732
5733 resetKeyRepeatLocked();
5734 releasePendingEventLocked();
5735 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005736 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005738 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005739 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740}
5741
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005742void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005743 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744 dumpDispatchStateLocked(dump);
5745
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005746 std::istringstream stream(dump);
5747 std::string line;
5748
5749 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005750 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752}
5753
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005754std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005755 std::string dump;
5756
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005757 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5758 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005759
5760 std::string windowName = "None";
5761 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005762 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005763 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5764 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5765 : "token has capture without window";
5766 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005767 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005768
5769 return dump;
5770}
5771
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005772void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005773 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5774 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5775 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005776 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
Tiger Huang721e26f2018-07-24 22:26:19 +08005778 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5779 dump += StringPrintf(INDENT "FocusedApplications:\n");
5780 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5781 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005782 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005783 const std::chrono::duration timeout =
5784 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005785 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005786 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005787 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005790 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005792
Vishnu Nairc519ff72021-01-21 08:23:08 -08005793 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005794 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005796 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005797 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005798 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005799 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5800 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 }
5802 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005803 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804 }
5805
arthurhung6d4bed92021-03-17 11:59:33 +08005806 if (mDragState) {
5807 dump += StringPrintf(INDENT "DragState:\n");
5808 mDragState->dump(dump, INDENT2);
5809 }
5810
Arthur Hungb92218b2018-08-14 12:00:21 +08005811 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005812 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5813 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5814 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5815 const auto& displayInfo = it->second;
5816 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5817 displayInfo.logicalHeight);
5818 displayInfo.transform.dump(dump, "transform", INDENT4);
5819 } else {
5820 dump += INDENT2 "No DisplayInfo found!\n";
5821 }
5822
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005823 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005824 dump += INDENT2 "Windows:\n";
5825 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005826 dump += StringPrintf(INDENT3 "%zu: %s", i,
5827 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005828 }
5829 } else {
5830 dump += INDENT2 "Windows: <none>\n";
5831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832 }
5833 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005834 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835 }
5836
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005837 if (!mGlobalMonitorsByDisplay.empty()) {
5838 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5839 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005840 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005843 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
5845
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005846 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847
5848 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005849 if (!mRecentQueue.empty()) {
5850 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005851 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005852 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005853 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005854 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 }
5856 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005857 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 }
5859
5860 // Dump event currently being dispatched.
5861 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005862 dump += INDENT "PendingEvent:\n";
5863 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005864 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005865 dump += StringPrintf(", age=%" PRId64 "ms\n",
5866 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005868 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 }
5870
5871 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005872 if (!mInboundQueue.empty()) {
5873 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005874 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005875 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005876 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005877 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005878 }
5879 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005880 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 }
5882
Prabir Pradhancef936d2021-07-21 16:17:52 +00005883 if (!mCommandQueue.empty()) {
5884 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5885 } else {
5886 dump += INDENT "CommandQueue: <empty>\n";
5887 }
5888
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005889 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005890 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005891 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005892 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005893 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005894 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005895 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005896 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005897 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005899 if (!connection->outboundQueue.empty()) {
5900 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5901 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005902 dump += dumpQueue(connection->outboundQueue, currentTime);
5903
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005905 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 }
5907
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005908 if (!connection->waitQueue.empty()) {
5909 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5910 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005911 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005913 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005915 std::string inputStateDump = streamableToString(connection->inputState);
5916 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005917 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005918 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 }
5921 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005922 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 }
5924
Antonio Kantek15beb512022-06-13 22:35:41 +00005925 if (!mTouchModePerDisplay.empty()) {
5926 dump += INDENT "TouchModePerDisplay:\n";
5927 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5928 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5929 std::to_string(touchMode).c_str());
5930 }
5931 } else {
5932 dump += INDENT "TouchModePerDisplay: <none>\n";
5933 }
5934
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005935 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005936 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5937 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5938 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005939 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005940 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005941 dump += INDENT "InputTracer: ";
5942 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943}
5944
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005945void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005946 const size_t numMonitors = monitors.size();
5947 for (size_t i = 0; i < numMonitors; i++) {
5948 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005949 const std::shared_ptr<Connection>& connection = monitor.connection;
5950 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005951 dump += "\n";
5952 }
5953}
5954
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005955class LooperEventCallback : public LooperCallback {
5956public:
5957 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5958 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5959
5960private:
5961 std::function<int(int events)> mCallback;
5962};
5963
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005964Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005965 if (DEBUG_CHANNEL_CREATION) {
5966 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005969 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005970 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005971 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005972
5973 if (result) {
5974 return base::Error(result) << "Failed to open input channel pair with name " << name;
5975 }
5976
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005978 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005979 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005980 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005981 std::shared_ptr<Connection> connection =
5982 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5983 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005985 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5986 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005987 ALOGE("Created a new connection, but the token %p is already known", token.get());
5988 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005989
5990 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5991 this, std::placeholders::_1, token);
5992
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005993 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005994 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 } // release lock
5996
5997 // Wake the looper because some connections have changed.
5998 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005999 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000}
6001
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006002Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00006003 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006004 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006005 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07006006 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006007 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07006008 if (result) {
6009 return base::Error(result) << "Failed to open input channel pair with name " << name;
6010 }
6011
Michael Wright3dd60e22019-03-27 22:06:44 +00006012 { // acquire lock
6013 std::scoped_lock _l(mLock);
6014
6015 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07006016 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6017 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006018 }
6019
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006020 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006021 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006022 std::shared_ptr<Connection> connection =
6023 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6024 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006025
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006026 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6027 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006028 ALOGE("Created a new connection, but the token %p is already known", token.get());
6029 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006030
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006031 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6032 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006033
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006034 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006035
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006036 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006037 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006038 }
Garfield Tan15601662020-09-22 15:32:38 -07006039
Michael Wright3dd60e22019-03-27 22:06:44 +00006040 // Wake the looper because some connections have changed.
6041 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006042 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006043}
6044
Garfield Tan15601662020-09-22 15:32:38 -07006045status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006047 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048
Harry Cutts33476232023-01-30 19:57:29 +00006049 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 if (status) {
6051 return status;
6052 }
6053 } // release lock
6054
6055 // Wake the poll loop because removing the connection may have changed the current
6056 // synchronization state.
6057 mLooper->wake();
6058 return OK;
6059}
6060
Garfield Tan15601662020-09-22 15:32:38 -07006061status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6062 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006063 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006064 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006065 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 return BAD_VALUE;
6067 }
6068
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006069 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006070
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006072 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 }
6074
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006075 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076
6077 nsecs_t currentTime = now();
6078 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6079
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006080 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 return OK;
6082}
6083
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006084void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006085 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6086 auto& [displayId, monitors] = *it;
6087 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006088 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006089 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006090
Michael Wright3dd60e22019-03-27 22:06:44 +00006091 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006092 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006093 } else {
6094 ++it;
6095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 }
6097}
6098
Michael Wright3dd60e22019-03-27 22:06:44 +00006099status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006100 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006101 return pilferPointersLocked(token);
6102}
Michael Wright3dd60e22019-03-27 22:06:44 +00006103
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006104status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006105 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6106 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006107 LOG(WARNING)
6108 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006109 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006110 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006111
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006112 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006113 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006114 LOG(WARNING)
6115 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6116 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006117 return BAD_VALUE;
6118 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006119 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006120 if (deviceIds.empty()) {
6121 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006122 return BAD_VALUE;
6123 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006124
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006125 for (const DeviceId deviceId : deviceIds) {
6126 TouchState& state = *statePtr;
6127 TouchedWindow& window = *windowPtr;
6128 // Send cancel events to all the input channels we're stealing from.
6129 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6130 "input channel stole pointer stream");
6131 options.deviceId = deviceId;
6132 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006133 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6134 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006135 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006136
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006137 std::string canceledWindows;
6138 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006139 if (w.windowHandle->getToken() != token) {
6140 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006141 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006142 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006143 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006144 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006145 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006146 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006147 << " is stealing input gesture for device " << deviceId << " from "
6148 << canceledWindows;
6149
6150 // Prevent the gesture from being sent to any other windows.
6151 // This only blocks relevant pointers to be sent to other windows
6152 window.addPilferingPointers(deviceId, pointerIds);
6153
6154 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006155 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006156 return OK;
6157}
6158
Prabir Pradhan99987712020-11-10 18:43:05 -08006159void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6160 { // acquire lock
6161 std::scoped_lock _l(mLock);
6162 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006163 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006164 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6165 windowHandle != nullptr ? windowHandle->getName().c_str()
6166 : "token without window");
6167 }
6168
Vishnu Nairc519ff72021-01-21 08:23:08 -08006169 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006170 if (focusedToken != windowToken) {
6171 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6172 enabled ? "enable" : "disable");
6173 return;
6174 }
6175
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006176 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006177 ALOGW("Ignoring request to %s Pointer Capture: "
6178 "window has %s requested pointer capture.",
6179 enabled ? "enable" : "disable", enabled ? "already" : "not");
6180 return;
6181 }
6182
Christine Franksb768bb42021-11-29 12:11:31 -08006183 if (enabled) {
6184 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6185 mIneligibleDisplaysForPointerCapture.end(),
6186 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6187 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6188 return;
6189 }
6190 }
6191
Prabir Pradhan99987712020-11-10 18:43:05 -08006192 setPointerCaptureLocked(enabled);
6193 } // release lock
6194
6195 // Wake the thread to process command entries.
6196 mLooper->wake();
6197}
6198
Christine Franksb768bb42021-11-29 12:11:31 -08006199void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6200 { // acquire lock
6201 std::scoped_lock _l(mLock);
6202 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6203 if (!isEligible) {
6204 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6205 }
6206 } // release lock
6207}
6208
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006209std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006210 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006211 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006212 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006213 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006214 }
6215 }
6216 }
6217 return std::nullopt;
6218}
6219
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006220std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6221 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006222 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006223 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006224 }
6225
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006226 for (const auto& [token, connection] : mConnectionsByToken) {
6227 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006228 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 }
6230 }
Robert Carr4e670e52018-08-15 13:26:12 -07006231
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006232 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233}
6234
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006235std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006236 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006237 if (connection == nullptr) {
6238 return "<nullptr>";
6239 }
6240 return connection->getInputChannelName();
6241}
6242
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006243void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006244 mAnrTracker.eraseToken(connection->getToken());
6245 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006246}
6247
Prabir Pradhancef936d2021-07-21 16:17:52 +00006248void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006249 const std::shared_ptr<Connection>& connection,
6250 uint32_t seq, bool handled,
6251 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006253 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006254
6255 { // Start critical section
6256 auto dispatchEntryIt =
6257 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6258 [seq](auto& e) { return e->seq == seq; });
6259 if (dispatchEntryIt == connection->waitQueue.end()) {
6260 return;
6261 }
6262
6263 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6264
6265 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6266 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006267 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006268 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6269 }
6270 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006271 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006272 dispatchEntry.deliveryTime, consumeTime, finishTime);
6273 }
6274
6275 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006276 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6277 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006278 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006279 }
6280 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006281
6282 // Dequeue the event and start the next cycle.
6283 // Because the lock might have been released, it is possible that the
6284 // contents of the wait queue to have been drained, so we need to double-check
6285 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006286 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6287 [seq](auto& e) { return e->seq == seq; });
6288 if (entryIt != connection->waitQueue.end()) {
6289 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6290 connection->waitQueue.erase(entryIt);
6291
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006292 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6294 if (!connection->responsive) {
6295 connection->responsive = isConnectionResponsive(*connection);
6296 if (connection->responsive) {
6297 // The connection was unresponsive, and now it's responsive.
6298 processConnectionResponsiveLocked(*connection);
6299 }
6300 }
6301 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006302 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006303 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6304 // Only dispatch fallbacks if there is a window for the connection.
6305 if (windowHandle != nullptr) {
6306 const auto inputTarget =
6307 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6308 dispatchEntry->targetFlags,
6309 fallbackKeyEntry->downTime);
6310 if (inputTarget.has_value()) {
6311 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6312 *inputTarget);
6313 }
6314 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006316 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006317 }
6318
6319 // Start the next dispatch cycle for this connection.
6320 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321}
6322
Prabir Pradhancef936d2021-07-21 16:17:52 +00006323void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6324 const sp<IBinder>& newToken) {
6325 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6326 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006327 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006328 };
6329 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330}
6331
Prabir Pradhancef936d2021-07-21 16:17:52 +00006332void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6333 auto command = [this, token, x, y]() REQUIRES(mLock) {
6334 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006335 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006336 };
6337 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006338}
6339
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006340void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006341 if (connection == nullptr) {
6342 LOG_ALWAYS_FATAL("Caller must check for nullness");
6343 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006344 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6345 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006346 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006347 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006348 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006349 return;
6350 }
6351 /**
6352 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6353 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6354 * has changed. This could cause newer entries to time out before the already dispatched
6355 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6356 * processes the events linearly. So providing information about the oldest entry seems to be
6357 * most useful.
6358 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006359 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6360 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006361 std::string reason =
6362 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006363 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006364 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006365 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006366 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006367 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006368
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006369 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6370
6371 // Stop waking up for events on this connection, it is already unresponsive
6372 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006373}
6374
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006375void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6376 std::string reason =
6377 StringPrintf("%s does not have a focused window", application->getName().c_str());
6378 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006379
Yabin Cui8eb9c552023-06-08 18:05:07 +00006380 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006381 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006382 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006383 };
6384 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006385}
6386
chaviw98318de2021-05-19 16:45:23 -05006387void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006388 const std::string& reason) {
6389 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6390 updateLastAnrStateLocked(windowLabel, reason);
6391}
6392
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006393void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6394 const std::string& reason) {
6395 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006396 updateLastAnrStateLocked(windowLabel, reason);
6397}
6398
6399void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6400 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006402 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 struct tm tm;
6404 localtime_r(&t, &tm);
6405 char timestr[64];
6406 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006407 mLastAnrState.clear();
6408 mLastAnrState += INDENT "ANR:\n";
6409 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006410 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6411 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006412 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413}
6414
Prabir Pradhancef936d2021-07-21 16:17:52 +00006415void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006416 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006417 const KeyEvent event = createKeyEvent(entry);
6418 nsecs_t delay = 0;
6419 { // release lock
6420 scoped_unlock unlock(mLock);
6421 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006422 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006423 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6424 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6425 std::to_string(t.duration().count()).c_str());
6426 }
6427 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006428
6429 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006430 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006431 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006432 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006434 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006435 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006437}
6438
Prabir Pradhancef936d2021-07-21 16:17:52 +00006439void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006440 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006441 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006442 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006443 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006444 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006445 };
6446 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006447}
6448
Prabir Pradhanedd96402022-02-15 01:46:16 -08006449void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006450 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006451 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006452 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006453 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006454 };
6455 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006456}
6457
6458/**
6459 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6460 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6461 * command entry to the command queue.
6462 */
6463void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6464 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006465 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006466 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006467 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006468 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006469 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006470 pid = findMonitorPidByTokenLocked(connectionToken);
6471 } else {
6472 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006473 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006474 reason.c_str());
6475 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6476 if (handle != nullptr) {
6477 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006478 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006479 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006480 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006481}
6482
6483/**
6484 * Tell the policy that a connection has become responsive so that it can stop ANR.
6485 */
6486void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006487 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006488 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006489 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006490 pid = findMonitorPidByTokenLocked(connectionToken);
6491 } else {
6492 // The connection is a window
6493 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6494 if (handle != nullptr) {
6495 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006496 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006497 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006498 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006499}
6500
Prabir Pradhan24047542023-11-02 17:14:59 +00006501std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006502 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006503 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006504 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006505 if (!handled) {
6506 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006507 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006508 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006509 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 // Get the fallback key state.
6513 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006514 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006515 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006516 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517 connection->inputState.removeFallbackKey(originalKeyCode);
6518 }
6519
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006520 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006521 // If the application handles the original key for which we previously
6522 // generated a fallback or if the window is not a foreground window,
6523 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006524 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006525 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006526 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6527 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6528 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6529 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6530 keyEntry.policyFlags);
6531 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006532 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534
6535 mLock.unlock();
6536
Prabir Pradhana41d2442023-04-20 21:30:40 +00006537 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006538 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6539 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006540 unhandledKeyFallback) {
6541 event = *unhandledKeyFallback;
6542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543
6544 mLock.lock();
6545
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006546 // Cancel the fallback key, but only if we still have a window for the channel.
6547 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006548 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006549 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6550 if (windowHandle != nullptr) {
6551 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6552 "application handled the original non-fallback key "
6553 "or is no longer a foreground target, "
6554 "canceling previously dispatched fallback key");
6555 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006556 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006559 connection->inputState.removeFallbackKey(originalKeyCode);
6560 }
6561 } else {
6562 // If the application did not handle a non-fallback key, first check
6563 // that we are in a good state to perform unhandled key event processing
6564 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006565 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006566 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6568 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6569 "since this is not an initial down. "
6570 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6571 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6572 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006573 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006576 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6578 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6579 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6580 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6581 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006582 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583
6584 mLock.unlock();
6585
Prabir Pradhana41d2442023-04-20 21:30:40 +00006586 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006587 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6588 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006589 fb) {
6590 fallback = true;
6591 event = *fb;
6592 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006593
6594 mLock.lock();
6595
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006596 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006597 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006598 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006599 }
6600
6601 // Latch the fallback keycode for this key on an initial down.
6602 // The fallback keycode cannot change at any other point in the lifecycle.
6603 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006605 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006606 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006607 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006608 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006609 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610 }
6611
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006612 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006613
6614 // Cancel the fallback key if the policy decides not to send it anymore.
6615 // We will continue to dispatch the key to the policy but we will no
6616 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006617 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6618 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006619 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6620 if (fallback) {
6621 ALOGD("Unhandled key event: Policy requested to send key %d"
6622 "as a fallback for %d, but on the DOWN it had requested "
6623 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006624 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006625 } else {
6626 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6627 "but on the DOWN it had requested to send %d. "
6628 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006630 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006631 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006632
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006633 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6634 if (windowHandle != nullptr) {
6635 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6636 "canceling fallback, policy no longer desires it");
6637 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006638 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006639 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006640
6641 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006642 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006643 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006644 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006645 }
6646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006648 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6649 {
6650 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006651 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006652 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006653 for (const auto& [key, value] : fallbackKeys) {
6654 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006655 }
6656 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6657 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006659 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006660
6661 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006662 // Return the fallback key that we want dispatched to the channel.
6663 std::unique_ptr<KeyEntry> newEntry =
6664 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6665 event.getEventTime(), event.getDeviceId(),
6666 event.getSource(), event.getDisplayId(),
6667 keyEntry.policyFlags, keyEntry.action,
6668 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6669 *fallbackKeyCode, event.getScanCode(),
6670 event.getMetaState(), event.getRepeatCount(),
6671 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006672 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6673 ALOGD("Unhandled key event: Dispatching fallback key. "
6674 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006675 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006676 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006677 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006678 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006679 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6680 ALOGD("Unhandled key event: No fallback key.");
6681 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006682
6683 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006684 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006685 }
6686 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006687 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688}
6689
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690void InputDispatcher::traceInboundQueueLengthLocked() {
6691 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006692 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 }
6694}
6695
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006696void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006697 if (ATRACE_ENABLED()) {
6698 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006699 snprintf(counterName, sizeof(counterName), "oq:%s",
6700 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006701 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 }
6703}
6704
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006705void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006706 if (ATRACE_ENABLED()) {
6707 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006708 snprintf(counterName, sizeof(counterName), "wq:%s",
6709 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006710 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006711 }
6712}
6713
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006714void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006715 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006716
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006717 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006718 dumpDispatchStateLocked(dump);
6719
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006720 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006721 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006722 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006723 }
6724}
6725
6726void InputDispatcher::monitor() {
6727 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006728 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006729 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006730 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006731}
6732
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006733/**
6734 * Wake up the dispatcher and wait until it processes all events and commands.
6735 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6736 * this method can be safely called from any thread, as long as you've ensured that
6737 * the work you are interested in completing has already been queued.
6738 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006739bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006740 /**
6741 * Timeout should represent the longest possible time that a device might spend processing
6742 * events and commands.
6743 */
6744 constexpr std::chrono::duration TIMEOUT = 100ms;
6745 std::unique_lock lock(mLock);
6746 mLooper->wake();
6747 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6748 return result == std::cv_status::no_timeout;
6749}
6750
Vishnu Naire798b472020-07-23 13:52:21 -07006751/**
6752 * Sets focus to the window identified by the token. This must be called
6753 * after updating any input window handles.
6754 *
6755 * Params:
6756 * request.token - input channel token used to identify the window that should gain focus.
6757 * request.focusedToken - the token that the caller expects currently to be focused. If the
6758 * specified token does not match the currently focused window, this request will be dropped.
6759 * If the specified focused token matches the currently focused window, the call will succeed.
6760 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6761 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6762 * when requesting the focus change. This determines which request gets
6763 * precedence if there is a focus change request from another source such as pointer down.
6764 */
Vishnu Nair958da932020-08-21 17:12:37 -07006765void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6766 { // acquire lock
6767 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006768 std::optional<FocusResolver::FocusChanges> changes =
6769 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6770 if (changes) {
6771 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006772 }
6773 } // release lock
6774 // Wake up poll loop since it may need to make new input dispatching choices.
6775 mLooper->wake();
6776}
6777
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006778void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6779 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006780 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006781 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6782 ? removedFocusedWindowHandle
6783 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6784 if (resolvedWindow == nullptr) {
6785 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006786 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006787 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6788 "focus left window");
6789 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6790 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006791 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006792 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006793 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006794 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006795 }
6796
Prabir Pradhan99987712020-11-10 18:43:05 -08006797 // If a window has pointer capture, then it must have focus. We need to ensure that this
6798 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6799 // If the window loses focus before it loses pointer capture, then the window can be in a state
6800 // where it has pointer capture but not focus, violating the contract. Therefore we must
6801 // dispatch the pointer capture event before the focus event. Since focus events are added to
6802 // the front of the queue (above), we add the pointer capture event to the front of the queue
6803 // after the focus events are added. This ensures the pointer capture event ends up at the
6804 // front.
6805 disablePointerCaptureForcedLocked();
6806
Vishnu Nairc519ff72021-01-21 08:23:08 -08006807 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006808 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006809 }
6810}
Vishnu Nair958da932020-08-21 17:12:37 -07006811
Prabir Pradhan99987712020-11-10 18:43:05 -08006812void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006813 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006814 return;
6815 }
6816
6817 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6818
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006819 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006820 setPointerCaptureLocked(false);
6821 }
6822
6823 if (!mWindowTokenWithPointerCapture) {
6824 // No need to send capture changes because no window has capture.
6825 return;
6826 }
6827
6828 if (mPendingEvent != nullptr) {
6829 // Move the pending event to the front of the queue. This will give the chance
6830 // for the pending event to be dropped if it is a captured event.
6831 mInboundQueue.push_front(mPendingEvent);
6832 mPendingEvent = nullptr;
6833 }
6834
6835 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006836 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006837 mInboundQueue.push_front(std::move(entry));
6838}
6839
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006840void InputDispatcher::setPointerCaptureLocked(bool enable) {
6841 mCurrentPointerCaptureRequest.enable = enable;
6842 mCurrentPointerCaptureRequest.seq++;
6843 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006844 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006845 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006846 };
6847 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006848}
6849
Vishnu Nair599f1412021-06-21 10:39:58 -07006850void InputDispatcher::displayRemoved(int32_t displayId) {
6851 { // acquire lock
6852 std::scoped_lock _l(mLock);
6853 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006854 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006855 setFocusedApplicationLocked(displayId, nullptr);
6856 // Call focus resolver to clean up stale requests. This must be called after input windows
6857 // have been removed for the removed display.
6858 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006859 // Reset pointer capture eligibility, regardless of previous state.
6860 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006861 // Remove the associated touch mode state.
6862 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006863 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006864 } // release lock
6865
6866 // Wake up poll loop since it may need to make new input dispatching choices.
6867 mLooper->wake();
6868}
6869
Patrick Williamsd828f302023-04-28 17:52:08 -05006870void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006871 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6872 {
6873 // acquire lock
6874 std::scoped_lock _l(mLock);
6875 logDispatchStateLocked();
6876 }
6877 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6878 result.error().message().c_str());
6879 };
chaviw15fab6f2021-06-07 14:15:52 -05006880 // The listener sends the windows as a flattened array. Separate the windows by display for
6881 // more convenient parsing.
6882 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006883 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006884 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006885 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006886 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006887
6888 { // acquire lock
6889 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006890
6891 // Ensure that we have an entry created for all existing displays so that if a displayId has
6892 // no windows, we can tell that the windows were removed from the display.
6893 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6894 handlesPerDisplay[displayId];
6895 }
6896
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006897 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006898 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006899 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6900 }
6901
6902 for (const auto& [displayId, handles] : handlesPerDisplay) {
6903 setInputWindowsLocked(handles, displayId);
6904 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006905
6906 if (update.vsyncId < mWindowInfosVsyncId) {
6907 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6908 ", current update vsync id: %" PRId64,
6909 mWindowInfosVsyncId, update.vsyncId);
6910 }
6911 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006912 }
6913 // Wake up poll loop since it may need to make new input dispatching choices.
6914 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006915}
6916
Vishnu Nair062a8672021-09-03 16:07:44 -07006917bool InputDispatcher::shouldDropInput(
6918 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006919 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6920 (windowHandle->getInfo()->inputConfig.test(
6921 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006922 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006923 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6924 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006925 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006926 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006927 windowHandle->getInfo()->displayId);
6928 return true;
6929 }
6930 return false;
6931}
6932
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006933void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006934 const gui::WindowInfosUpdate& update) {
6935 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006936}
6937
Arthur Hungdfd528e2021-12-08 13:23:04 +00006938void InputDispatcher::cancelCurrentTouch() {
6939 {
6940 std::scoped_lock _l(mLock);
6941 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006942 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006943 "cancel current touch");
6944 synthesizeCancelationEventsForAllConnectionsLocked(options);
6945
6946 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006947 }
6948 // Wake up poll loop since there might be work to do.
6949 mLooper->wake();
6950}
6951
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006952void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6953 std::scoped_lock _l(mLock);
6954 mMonitorDispatchingTimeout = timeout;
6955}
6956
Arthur Hungc539dbb2022-12-08 07:45:36 +00006957void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6958 const sp<WindowInfoHandle>& oldWindowHandle,
6959 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006960 TouchState& state, int32_t deviceId,
6961 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006962 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006963 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006964 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6965 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6966 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6967 newWindowHandle->getInfo()->inputConfig.test(
6968 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6969 const sp<WindowInfoHandle> oldWallpaper =
6970 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6971 const sp<WindowInfoHandle> newWallpaper =
6972 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6973 if (oldWallpaper == newWallpaper) {
6974 return;
6975 }
6976
6977 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006978 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006979 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006980 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006981 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006982 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006983 }
6984
6985 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006986 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6987 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006988 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006989 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006990 }
6991}
6992
6993void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6994 ftl::Flags<InputTarget::Flags> newTargetFlags,
6995 const sp<WindowInfoHandle> fromWindowHandle,
6996 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006997 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006998 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006999 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7000 fromWindowHandle->getInfo()->inputConfig.test(
7001 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7002 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
7003 toWindowHandle->getInfo()->inputConfig.test(
7004 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
7005
7006 const sp<WindowInfoHandle> oldWallpaper =
7007 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
7008 const sp<WindowInfoHandle> newWallpaper =
7009 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
7010 if (oldWallpaper == newWallpaper) {
7011 return;
7012 }
7013
7014 if (oldWallpaper != nullptr) {
7015 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
7016 "transferring touch focus to another window");
7017 state.removeWindowByToken(oldWallpaper->getToken());
7018 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7019 }
7020
7021 if (newWallpaper != nullptr) {
7022 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007023 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7024 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007025 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7026 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007027 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007028 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007029 std::shared_ptr<Connection> wallpaperConnection =
7030 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007031 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007032 std::shared_ptr<Connection> toConnection =
7033 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007034 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7035 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7036 wallpaperFlags);
7037 }
7038 }
7039}
7040
7041sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7042 const sp<WindowInfoHandle>& windowHandle) const {
7043 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7044 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7045 bool foundWindow = false;
7046 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7047 if (!foundWindow && otherHandle != windowHandle) {
7048 continue;
7049 }
7050 if (windowHandle == otherHandle) {
7051 foundWindow = true;
7052 continue;
7053 }
7054
7055 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7056 return otherHandle;
7057 }
7058 }
7059 return nullptr;
7060}
7061
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007062void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7063 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007064 std::scoped_lock _l(mLock);
7065
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007066 mConfig.keyRepeatTimeout = timeout.count();
7067 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007068}
7069
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007070bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7071 DeviceId deviceId, int32_t pointerId) {
7072 std::scoped_lock _l(mLock);
7073 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7074 if (touchStateIt == mTouchStatesByDisplay.end()) {
7075 return false;
7076 }
7077 for (const TouchedWindow& window : touchStateIt->second.windows) {
7078 if (window.windowHandle->getToken() == token &&
7079 (window.hasTouchingPointer(deviceId, pointerId) ||
7080 window.hasHoveringPointer(deviceId, pointerId))) {
7081 return true;
7082 }
7083 }
7084 return false;
7085}
7086
Garfield Tane84e6f92019-08-29 17:28:41 -07007087} // namespace android::inputdispatcher