blob: d2d3db3563d50228122f061b09c4790dfee6cdaa [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000057#include "trace/ThreadedBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010058
Michael Wrightd02c5b62014-02-10 15:10:22 -080059#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62#define INDENT4 " "
63
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080064using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070065using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080066using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000067using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070069using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050070using android::gui::FocusRequest;
71using android::gui::TouchOcclusionMode;
72using android::gui::WindowInfo;
73using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080074using android::os::InputEventInjectionResult;
75using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000076namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
Prabir Pradhancef936d2021-07-21 16:17:52 +000080namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000081
Prabir Pradhandae52792023-12-15 07:36:40 +000082// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
83// flag is enabled. When the flag is changed, tracing will only be available after reboot.
84bool isInputTracingEnabled() {
85 static const std::string buildType = base::GetProperty("ro.build.type", "user");
86 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
87 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
88}
89
Prabir Pradhanbb7a0202024-02-10 02:09:01 +000090// Create the input tracing backend that writes to perfetto from a single thread.
91std::unique_ptr<trace::InputTracingBackendInterface> createInputTracingBackendIfEnabled() {
92 if (!isInputTracingEnabled()) {
93 return nullptr;
94 }
95 return std::make_unique<trace::impl::ThreadedBackend<trace::impl::PerfettoBackend>>(
96 trace::impl::PerfettoBackend());
97}
98
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000099template <class Entry>
100void ensureEventTraced(const Entry& entry) {
101 if (!entry.traceTracker) {
102 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
103 }
104}
105
Prabir Pradhancef936d2021-07-21 16:17:52 +0000106// Temporarily releases a held mutex for the lifetime of the instance.
107// Named to match std::scoped_lock
108class scoped_unlock {
109public:
110 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
111 ~scoped_unlock() { mMutex.lock(); }
112
113private:
114 std::mutex& mMutex;
115};
116
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117// Default input dispatching timeout if there is no focused application or paused window
118// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800119const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
120 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
121 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800123// The default minimum time gap between two user activity poke events.
124const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
125
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800126const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000129constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
130
131// Log a warning when an interception call takes longer than this to process.
132constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133
134// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000135constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
136
Antonio Kantekea47acb2021-12-23 12:41:25 -0800137// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000138constexpr int LOGTAG_INPUT_INTERACTION = 62000;
139constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000140constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000141
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000142const ui::Transform kIdentityTransform;
143
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000144inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 return systemTime(SYSTEM_TIME_MONOTONIC);
146}
147
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700148inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000149 if (binder == nullptr) {
150 return "<null>";
151 }
152 return StringPrintf("%p", binder.get());
153}
154
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000155static std::string uidString(const gui::Uid& uid) {
156 return uid.toString();
157}
158
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AKEY_EVENT_ACTION_DOWN:
162 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700165 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 }
167}
168
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700169Result<void> validateKeyEvent(int32_t action) {
170 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171}
172
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700173Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700176 case AMOTION_EVENT_ACTION_UP: {
177 if (pointerCount != 1) {
178 return Error() << "invalid pointer count " << pointerCount;
179 }
180 return {};
181 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 case AMOTION_EVENT_ACTION_HOVER_ENTER:
184 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700185 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
186 if (pointerCount < 1) {
187 return Error() << "invalid pointer count " << pointerCount;
188 }
189 return {};
190 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800191 case AMOTION_EVENT_ACTION_CANCEL:
192 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700194 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800197 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700198 if (index < 0) {
199 return Error() << "invalid index " << index << " for "
200 << MotionEvent::actionToString(action);
201 }
202 if (index >= pointerCount) {
203 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
204 }
205 if (pointerCount <= 1) {
206 return Error() << "invalid pointer count " << pointerCount << " for "
207 << MotionEvent::actionToString(action);
208 }
209 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700210 }
211 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700212 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
213 if (actionButton == 0) {
214 return Error() << "action button should be nonzero for "
215 << MotionEvent::actionToString(action);
216 }
217 return {};
218 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700219 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700220 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
222}
223
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000224int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500225 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
226}
227
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700228Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
229 const PointerProperties* pointerProperties) {
230 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
231 if (!actionCheck.ok()) {
232 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
234 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700235 return Error() << "Motion event has invalid pointer count " << pointerCount
236 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800238 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 for (size_t i = 0; i < pointerCount; i++) {
240 int32_t id = pointerProperties[i].id;
241 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700242 return Error() << "Motion event has invalid pointer id " << id
243 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800245 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700246 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800248 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700250 return {};
251}
252
253Result<void> validateInputEvent(const InputEvent& event) {
254 switch (event.getType()) {
255 case InputEventType::KEY: {
256 const KeyEvent& key = static_cast<const KeyEvent&>(event);
257 const int32_t action = key.getAction();
258 return validateKeyEvent(action);
259 }
260 case InputEventType::MOTION: {
261 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
262 const int32_t action = motion.getAction();
263 const size_t pointerCount = motion.getPointerCount();
264 const PointerProperties* pointerProperties = motion.getPointerProperties();
265 const int32_t actionButton = motion.getActionButton();
266 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
267 }
268 default: {
269 return {};
270 }
271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800274std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
275 std::bitset<MAX_POINTER_ID + 1> pointerIds;
276 for (const PointerProperties& pointer : pointers) {
277 pointerIds.set(pointer.id);
278 }
279 return pointerIds;
280}
281
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000282std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000284 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 }
286
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000287 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 bool first = true;
289 Region::const_iterator cur = region.begin();
290 Region::const_iterator const tail = region.end();
291 while (cur != tail) {
292 if (first) {
293 first = false;
294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800295 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800297 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298 cur++;
299 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000300 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301}
302
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000303std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
304 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500305 constexpr size_t maxEntries = 50; // max events to print
306 constexpr size_t skipBegin = maxEntries / 2;
307 const size_t skipEnd = queue.size() - maxEntries / 2;
308 // skip from maxEntries / 2 ... size() - maxEntries/2
309 // only print from 0 .. skipBegin and then from skipEnd .. size()
310
311 std::string dump;
312 for (size_t i = 0; i < queue.size(); i++) {
313 const DispatchEntry& entry = *queue[i];
314 if (i >= skipBegin && i < skipEnd) {
315 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
316 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
317 continue;
318 }
319 dump.append(INDENT4);
320 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000321 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
322 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500323 ns2ms(currentTime - entry.eventEntry->eventTime));
324 if (entry.deliveryTime != 0) {
325 // This entry was delivered, so add information on how long we've been waiting
326 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
327 }
328 dump.append("\n");
329 }
330 return dump;
331}
332
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333/**
334 * Find the entry in std::unordered_map by key, and return it.
335 * If the entry is not found, return a default constructed entry.
336 *
337 * Useful when the entries are vectors, since an empty vector will be returned
338 * if the entry is not found.
339 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
340 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700341template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700343 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700344 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800345}
346
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000347bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700348 if (first == second) {
349 return true;
350 }
351
352 if (first == nullptr || second == nullptr) {
353 return false;
354 }
355
356 return first->getToken() == second->getToken();
357}
358
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000359bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000360 if (first == nullptr || second == nullptr) {
361 return false;
362 }
363 return first->applicationInfo.token != nullptr &&
364 first->applicationInfo.token == second->applicationInfo.token;
365}
366
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800367template <typename T>
368size_t firstMarkedBit(T set) {
369 // TODO: replace with std::countr_zero from <bit> when that's available
370 LOG_ALWAYS_FATAL_IF(set.none());
371 size_t i = 0;
372 while (!set.test(i)) {
373 i++;
374 }
375 return i;
376}
377
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000378std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
379 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000380 std::shared_ptr<const EventEntry> eventEntry,
381 ftl::Flags<InputTarget::Flags> inputTargetFlags,
382 int64_t vsyncId) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000383 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000384 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
385 const std::optional<int32_t> windowId =
386 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
387 // Assume the only targets that are not associated with a window are global monitors, and use
388 // the system UID for global monitors for tracing purposes.
389 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000390
391 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700392 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700393 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700394 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000395 inputTarget.globalScaleFactor, uid, vsyncId,
396 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000397 }
398
399 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
400 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
401
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000402 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000404 const ui::Transform* transform = &kIdentityTransform;
405 const ui::Transform* displayTransform = &kIdentityTransform;
406 if (zeroCoords) {
407 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
408 } else {
409 // Use the first pointer information to normalize all other pointers. This could be any
410 // pointer as long as all other pointers are normalized to the same value and the final
411 // DispatchEntry uses the transform for the normalized pointer.
412 transform =
413 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
414 const ui::Transform inverseTransform = transform->inverse();
415 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000416
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000417 // Iterate through all pointers in the event to normalize against the first.
418 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
419 PointerCoords& newCoords = pointerCoords[i];
420 const auto pointerId = motionEntry.pointerProperties[i].id;
421 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000422
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000423 newCoords.copyFrom(motionEntry.pointerCoords[i]);
424 // First, apply the current pointer's transform to update the coordinates into
425 // window space.
426 newCoords.transform(currTransform);
427 // Next, apply the inverse transform of the normalized coordinates so the
428 // current coordinates are transformed into the normalized coordinate space.
429 newCoords.transform(inverseTransform);
430 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431 }
432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700433 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000434 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000435 motionEntry.eventTime, motionEntry.deviceId,
436 motionEntry.source, motionEntry.displayId,
437 motionEntry.policyFlags, motionEntry.action,
438 motionEntry.actionButton, motionEntry.flags,
439 motionEntry.metaState, motionEntry.buttonState,
440 motionEntry.classification, motionEntry.edgeFlags,
441 motionEntry.xPrecision, motionEntry.yPrecision,
442 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
443 motionEntry.downTime, motionEntry.pointerProperties,
444 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000445
446 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700447 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000448 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000449 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000450 return dispatchEntry;
451}
452
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500453template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500455 if (lhs == nullptr && rhs == nullptr) {
456 return true;
457 }
458 if (lhs == nullptr || rhs == nullptr) {
459 return false;
460 }
461 return *lhs == *rhs;
462}
463
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000464KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000465 KeyEvent event;
466 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
467 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
468 entry.repeatCount, entry.downTime, entry.eventTime);
469 return event;
470}
471
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000472bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000473 // Do not keep track of gesture monitors. They receive every event and would disproportionately
474 // affect the statistics.
475 if (connection.monitor) {
476 return false;
477 }
478 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
479 if (!connection.responsive) {
480 return false;
481 }
482 return true;
483}
484
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000485bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000486 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
487 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000488 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
489 return false;
490 }
491 // Only track latency for events that originated from hardware
492 if (eventEntry.isSynthesized()) {
493 return false;
494 }
495 const EventEntry::Type& inputEventEntryType = eventEntry.type;
496 if (inputEventEntryType == EventEntry::Type::KEY) {
497 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
498 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
499 return false;
500 }
501 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
502 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
503 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
504 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
505 return false;
506 }
507 } else {
508 // Not a key or a motion
509 return false;
510 }
511 if (!shouldReportMetricsForConnection(connection)) {
512 return false;
513 }
514 return true;
515}
516
Prabir Pradhancef936d2021-07-21 16:17:52 +0000517/**
518 * Connection is responsive if it has no events in the waitQueue that are older than the
519 * current time.
520 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000521bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000522 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000523 for (const auto& dispatchEntry : connection.waitQueue) {
524 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000525 return false;
526 }
527 }
528 return true;
529}
530
Antonio Kantekf16f2832021-09-28 04:39:20 +0000531// Returns true if the event type passed as argument represents a user activity.
532bool isUserActivityEvent(const EventEntry& eventEntry) {
533 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000534 case EventEntry::Type::CONFIGURATION_CHANGED:
535 case EventEntry::Type::DEVICE_RESET:
536 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000537 case EventEntry::Type::FOCUS:
538 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000539 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000540 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000541 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000542 case EventEntry::Type::KEY:
543 case EventEntry::Type::MOTION:
544 return true;
545 }
546}
547
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000549bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000550 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800551 const auto inputConfig = windowInfo.inputConfig;
552 if (windowInfo.displayId != displayId ||
553 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800554 return false;
555 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700556 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800557 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800558 return false;
559 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000560
561 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
562 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
563 // the window. Points on the right and bottom edges should not be inside the window, so we need
564 // to be careful about performing a hit test when the display is rotated, since the "right" and
565 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
566 // logical display in which WM determined the bounds. Perform the hit test in the logical
567 // display space to ensure these edges are considered correctly in all orientations.
568 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
569 const auto p = displayTransform.transform(x, y);
570 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800571 return false;
572 }
573 return true;
574}
575
Prabir Pradhand65552b2021-10-07 11:23:50 -0700576bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
577 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000578 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700579}
580
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800581// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000582// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
583// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
584// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800585// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000586bool canReceiveForegroundTouches(const WindowInfo& info) {
587 // A non-touchable window can still receive touch events (e.g. in the case of
588 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
589 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
590}
591
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000592bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700593 if (windowHandle == nullptr) {
594 return false;
595 }
596 const WindowInfo* windowInfo = windowHandle->getInfo();
597 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
598 return true;
599 }
600 return false;
601}
602
Prabir Pradhan5735a322022-04-11 17:23:34 +0000603// Checks targeted injection using the window's owner's uid.
604// Returns an empty string if an entry can be sent to the given window, or an error message if the
605// entry is a targeted injection whose uid target doesn't match the window owner.
606std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
607 const EventEntry& entry) {
608 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
609 // The event was not injected, or the injected event does not target a window.
610 return {};
611 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000612 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000613 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000614 return StringPrintf("No valid window target for injection into uid %s.",
615 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000616 }
617 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000618 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
619 "owned by uid %s.",
620 uid.toString().c_str(), window->getName().c_str(),
621 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000622 }
623 return {};
624}
625
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000626std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700627 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
628 // Always dispatch mouse events to cursor position.
629 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000630 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700631 }
632
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700633 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000634 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
635 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700636}
637
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700638std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
639 if (eventEntry.type == EventEntry::Type::KEY) {
640 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
641 return keyEntry.downTime;
642 } else if (eventEntry.type == EventEntry::Type::MOTION) {
643 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
644 return motionEntry.downTime;
645 }
646 return std::nullopt;
647}
648
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000649/**
650 * Compare the old touch state to the new touch state, and generate the corresponding touched
651 * windows (== input targets).
652 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
653 * If the pointer just entered the new window, produce HOVER_ENTER.
654 * For pointers remaining in the window, produce HOVER_MOVE.
655 */
656std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
657 const TouchState& newTouchState,
658 const MotionEntry& entry) {
659 std::vector<TouchedWindow> out;
660 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700661
662 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
663 // ACTION_SCROLL events should not affect the hovering pointer dispatch
664 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000665 }
666
667 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800668 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000669
670 std::set<sp<WindowInfoHandle>> oldWindows;
671 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800672 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 }
674
675 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800676 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677
678 // If the pointer is no longer in the new window set, send HOVER_EXIT.
679 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
680 if (newWindows.find(oldWindow) == newWindows.end()) {
681 TouchedWindow touchedWindow;
682 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000683 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 out.push_back(touchedWindow);
685 }
686 }
687
688 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
689 TouchedWindow touchedWindow;
690 touchedWindow.windowHandle = newWindow;
691 if (oldWindows.find(newWindow) == oldWindows.end()) {
692 // Any windows that have this pointer now, and didn't have it before, should get
693 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000694 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000695 } else {
696 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700697 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700698 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000699 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
700 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700701 // The Accessibility injected touch exploration event stream
702 // has known inconsistencies, so log ERROR instead of
703 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700704 severity = android::base::LogSeverity::ERROR;
705 }
706 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700707 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000708 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000709 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800710 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000711 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
712 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
713 }
714 out.push_back(touchedWindow);
715 }
716 return out;
717}
718
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800719template <typename T>
720std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
721 left.insert(left.end(), right.begin(), right.end());
722 return left;
723}
724
Harry Cuttsb166c002023-05-09 13:06:05 +0000725// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
726// both.
727void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
728 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
729 if (!window.windowHandle->getInfo()->inputConfig.test(
730 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
731 // In addition to TouchState, erase this window from the input targets! We don't have a
732 // good way to do this today except by adding a nested loop.
733 // TODO(b/282025641): simplify this code once InputTargets are being identified
734 // separately from TouchedWindows.
735 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800736 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000737 });
738 return true;
739 }
740 return false;
741 });
742}
743
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700744/**
745 * In general, touch should be always split between windows. Some exceptions:
746 * 1. Don't split touch if all of the below is true:
747 * (a) we have an active pointer down *and*
748 * (b) a new pointer is going down that's from the same device *and*
749 * (c) the window that's receiving the current pointer does not support split touch.
750 * 2. Don't split mouse events
751 */
752bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
753 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
754 // We should never split mouse events
755 return false;
756 }
757 for (const TouchedWindow& touchedWindow : touchState.windows) {
758 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
759 // Spy windows should not affect whether or not touch is split.
760 continue;
761 }
762 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
763 continue;
764 }
765 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
766 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
767 // Wallpaper window should not affect whether or not touch is split
768 continue;
769 }
770
771 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
772 return false;
773 }
774 }
775 return true;
776}
777
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700778/**
779 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
780 */
781bool isStylusActiveInDisplay(
782 int32_t displayId,
783 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
784 const auto it = touchStatesByDisplay.find(displayId);
785 if (it == touchStatesByDisplay.end()) {
786 return false;
787 }
788 const TouchState& state = it->second;
789 return state.hasActiveStylus();
790}
791
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800792Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
793 struct HashFunction {
794 size_t operator()(const WindowInfo& info) const { return info.id; }
795 };
796
797 std::unordered_set<WindowInfo, HashFunction> windowSet;
798 for (const WindowInfo& info : update.windowInfos) {
799 const auto [_, inserted] = windowSet.insert(info);
800 if (!inserted) {
801 return Error() << "Duplicate entry for " << info;
802 }
803 }
804 return {};
805}
806
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800807int32_t getUserActivityEventType(const EventEntry& eventEntry) {
808 switch (eventEntry.type) {
809 case EventEntry::Type::KEY: {
810 return USER_ACTIVITY_EVENT_BUTTON;
811 }
812 case EventEntry::Type::MOTION: {
813 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
814 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
815 return USER_ACTIVITY_EVENT_TOUCH;
816 }
817 return USER_ACTIVITY_EVENT_OTHER;
818 }
819 default: {
820 LOG_ALWAYS_FATAL("%s events are not user activity",
821 ftl::enum_string(eventEntry.type).c_str());
822 }
823 }
824}
825
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000826std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
827 CancelationOptions::Mode mode) {
828 switch (mode) {
829 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
830 return {true, true};
831 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
832 return {true, false};
833 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
834 return {false, true};
835 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
836 return {false, true};
837 }
838}
839
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000840} // namespace
841
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842// --- InputDispatcher ---
843
Prabir Pradhana41d2442023-04-20 21:30:40 +0000844InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000845 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000846
847InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
848 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700849 : mPolicy(policy),
850 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800852 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800853 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700854 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800855 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700856 mDispatchEnabled(false),
857 mDispatchFrozen(false),
858 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100859 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000860 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800861 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000862 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000863 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700864 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800865 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700867 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700868#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700869 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700870#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700871 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000872
873 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000874 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000875 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800876
877 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
880InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000881 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882
Prabir Pradhancef936d2021-07-21 16:17:52 +0000883 resetKeyRepeatLocked();
884 releasePendingEventLocked();
885 drainInboundQueueLocked();
886 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000888 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700889 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800890 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892}
893
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700894status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700895 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700896 return ALREADY_EXISTS;
897 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700898 mThread = std::make_unique<InputThread>(
899 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
900 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700901}
902
903status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700904 if (mThread && mThread->isCallingThread()) {
905 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700906 return INVALID_OPERATION;
907 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700908 mThread.reset();
909 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700910}
911
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700913 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800915 std::scoped_lock _l(mLock);
916 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917
918 // Run a dispatch loop if there are no pending commands.
919 // The dispatch loop might enqueue commands to run afterwards.
920 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800921 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923
924 // Run all pending commands if there are any.
925 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000926 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700927 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 // If we are still waiting for ack on some events,
931 // we might have to wake up earlier to check if an app is anr'ing.
932 const nsecs_t nextAnrCheck = processAnrsLocked();
933 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
934
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800935 // We are about to enter an infinitely long sleep, because we have no commands or
936 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700937 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800938 mDispatcherEnteredIdle.notify_all();
939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 } // release lock
941
942 // Wait for callback or timeout or wake. (make sure we round up, not down)
943 nsecs_t currentTime = now();
944 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
945 mLooper->pollOnce(timeoutMillis);
946}
947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500949 * Raise ANR if there is no focused window.
950 * Before the ANR is raised, do a final state check:
951 * 1. The currently focused application must be the same one we are waiting for.
952 * 2. Ensure we still don't have a focused window.
953 */
954void InputDispatcher::processNoFocusedWindowAnrLocked() {
955 // Check if the application that we are waiting for is still focused.
956 std::shared_ptr<InputApplicationHandle> focusedApplication =
957 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
958 if (focusedApplication == nullptr ||
959 focusedApplication->getApplicationToken() !=
960 mAwaitedFocusedApplication->getApplicationToken()) {
961 // Unexpected because we should have reset the ANR timer when focused application changed
962 ALOGE("Waited for a focused window, but focused application has already changed to %s",
963 focusedApplication->getName().c_str());
964 return; // The focused application has changed.
965 }
966
chaviw98318de2021-05-19 16:45:23 -0500967 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500968 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
969 if (focusedWindowHandle != nullptr) {
970 return; // We now have a focused window. No need for ANR.
971 }
972 onAnrLocked(mAwaitedFocusedApplication);
973}
974
975/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700976 * Check if any of the connections' wait queues have events that are too old.
977 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
978 * Return the time at which we should wake up next.
979 */
980nsecs_t InputDispatcher::processAnrsLocked() {
981 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700982 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700983 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
984 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
985 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500986 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700987 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500988 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700989 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700990 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500991 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
993 }
994 }
995
996 // Check if any connection ANRs are due
997 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
998 if (currentTime < nextAnrCheck) { // most likely scenario
999 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1000 }
1001
1002 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001003 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 if (connection == nullptr) {
1005 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1006 return nextAnrCheck;
1007 }
1008 connection->responsive = false;
1009 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001010 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001011 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001012 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001013}
1014
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001015std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001016 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001017 if (connection->monitor) {
1018 return mMonitorDispatchingTimeout;
1019 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001020 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001021 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001022 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001023 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001024 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025}
1026
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001027void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 nsecs_t currentTime = now();
1029
Jeff Browndc5992e2014-04-11 01:27:26 -07001030 // Reset the key repeat timer whenever normal dispatch is suspended while the
1031 // device is in a non-interactive state. This is to ensure that we abort a key
1032 // repeat if the device is just coming out of sleep.
1033 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 resetKeyRepeatLocked();
1035 }
1036
1037 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1038 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001039 if (DEBUG_FOCUS) {
1040 ALOGD("Dispatch frozen. Waiting some more.");
1041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 return;
1043 }
1044
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 // Ready to start a new event.
1046 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 // Synthesize a key repeat if appropriate.
1050 if (mKeyRepeatState.lastKeyEntry) {
1051 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1052 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1053 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001054 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
1057
1058 // Nothing to do if there is no pending event.
1059 if (!mPendingEvent) {
1060 return;
1061 }
1062 } else {
1063 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 mPendingEvent = mInboundQueue.front();
1065 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 traceInboundQueueLengthLocked();
1067 }
1068
1069 // Poke user activity for this event.
1070 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001071 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074
1075 // Now we have an event to dispatch.
1076 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085
1086 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089
1090 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001091 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 const ConfigurationChangedEntry& typedEntry =
1093 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 break;
1097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001099 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const DeviceResetEntry& typedEntry =
1101 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 break;
1105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001107 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const FocusEntry> typedEntry =
1109 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001110 dispatchFocusLocked(currentTime, typedEntry);
1111 done = true;
1112 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1113 break;
1114 }
1115
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001116 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001118 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1119 done = true;
1120 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1121 break;
1122 }
1123
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1125 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001126 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1128 done = true;
1129 break;
1130 }
1131
arthurhungb89ccb02020-12-30 16:19:01 +08001132 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const DragEntry> typedEntry =
1134 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001135 dispatchDragLocked(currentTime, typedEntry);
1136 done = true;
1137 break;
1138 }
1139
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001141 std::shared_ptr<const KeyEntry> keyEntry =
1142 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1147 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001150 if (done && mTracer) {
1151 ensureEventTraced(*keyEntry);
1152 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1153 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 break;
1155 }
1156
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001158 std::shared_ptr<const MotionEntry> motionEntry =
1159 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001161 // The event is stale. However, only drop stale events if there isn't an ongoing
1162 // gesture. That would allow us to complete the processing of the current stroke.
1163 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1164 if (touchStateIt != mTouchStatesByDisplay.end()) {
1165 const TouchState& touchState = touchStateIt->second;
1166 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1167 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1168 dropReason = DropReason::STALE;
1169 }
1170 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001171 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001172 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001173 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1174 // Only drop events that are focus-dispatched.
1175 dropReason = DropReason::BLOCKED;
1176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001178 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001179 if (done && mTracer) {
1180 ensureEventTraced(*motionEntry);
1181 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1182 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
Chris Yef59a2f42020-10-16 12:55:26 -07001185
1186 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001187 std::shared_ptr<const SensorEntry> sensorEntry =
1188 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001189
Chris Yef59a2f42020-10-16 12:55:26 -07001190 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1191 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1192 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1193 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1194 dropReason = DropReason::STALE;
1195 }
1196 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1197 done = true;
1198 break;
1199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201
1202 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001203 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
Michael Wright3a981722015-06-10 15:26:13 +01001206 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
1208 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001209 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
1211}
1212
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001213bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001214 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001215}
1216
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001217/**
1218 * Return true if the events preceding this incoming motion event should be dropped
1219 * Return false otherwise (the default behaviour)
1220 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001221bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001222 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001223 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224
1225 // Optimize case where the current application is unresponsive and the user
1226 // decides to touch a window in a different application.
1227 // If the application takes too long to catch up then we drop all events preceding
1228 // the touch into the other window.
1229 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001230 const int32_t displayId = motionEntry.displayId;
1231 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001232 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001233
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001234 sp<WindowInfoHandle> touchedWindowHandle =
1235 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001236 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001237 touchedWindowHandle->getApplicationToken() !=
1238 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001239 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 ALOGI("Pruning input queue because user touched a different application while waiting "
1241 "for %s",
1242 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001243 return true;
1244 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001245
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001246 // Alternatively, maybe there's a spy window that could handle this event.
1247 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1248 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1249 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001250 const std::shared_ptr<Connection> connection =
1251 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001252 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001253 // This spy window could take more input. Drop all events preceding this
1254 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001255 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001256 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001257 mAwaitedFocusedApplication->getName().c_str());
1258 return true;
1259 }
1260 }
1261 }
1262
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001263 return false;
1264}
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001267 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001269 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 traceInboundQueueLengthLocked();
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001273 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001274 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1275 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001278 if (mTracer) {
1279 ensureEventTraced(keyEntry);
1280 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001281
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001282 // If a new up event comes in, and the pending event with same key code has been asked
1283 // to try again later because of the policy. We have to reset the intercept key wake up
1284 // time for it may have been handled in the policy and could be dropped.
1285 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1286 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001287 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001288 if (pendingKey.keyCode == keyEntry.keyCode &&
1289 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001290 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1291 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001292 pendingKey.interceptKeyWakeupTime = 0;
1293 needWake = true;
1294 }
1295 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 break;
1297 }
1298
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001299 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001300 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1301 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001302 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1303 if (mTracer) {
1304 ensureEventTraced(motionEntry);
1305 }
1306 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001310
1311 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1312 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1313 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1314 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1315 // and some other events have not yet been processed, the dispatcher will wait for
1316 // these events to be processed before dispatching the key event. This is because
1317 // the unprocessed events may cause the focus to change (for example, by launching a
1318 // new window or tapping a different window). To prevent waiting too long, we force
1319 // the key to be sent to the currently focused window when a new tap comes in.
1320 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1321 "just send the pending key event to the currently focused window.");
1322 mKeyIsWaitingForEventsTimeout = now();
1323 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001326 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001327 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1328 break;
1329 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001330 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001331 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001333 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001334 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1335 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001336 // nothing to do
1337 break;
1338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 return needWake;
1342}
1343
Prabir Pradhan24047542023-11-02 17:14:59 +00001344void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001345 // Do not store sensor event in recent queue to avoid flooding the queue.
1346 if (entry->type != EventEntry::Type::SENSOR) {
1347 mRecentQueue.push_back(entry);
1348 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001349 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001350 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352}
1353
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001354sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1355 bool isStylus,
1356 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001358 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001359 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001360 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001361 continue;
1362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001364 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001365 if (!info.isSpy() &&
1366 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001367 return windowHandle;
1368 }
1369 }
1370 return nullptr;
1371}
1372
1373std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001374 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001375 if (touchedWindow == nullptr) {
1376 return {};
1377 }
1378 // Traverse windows from front to back until we encounter the touched window.
1379 std::vector<InputTarget> outsideTargets;
1380 const auto& windowHandles = getWindowHandlesLocked(displayId);
1381 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1382 if (windowHandle == touchedWindow) {
1383 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1384 // below the touched window will not get ACTION_OUTSIDE event.
1385 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001386 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001387
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001388 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001389 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001390 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1391 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001392 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1393 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001394 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
1396 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001397 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398}
1399
Prabir Pradhand65552b2021-10-07 11:23:50 -07001400std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001401 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001402 // Traverse windows from front to back and gather the touched spy windows.
1403 std::vector<sp<WindowInfoHandle>> spyWindows;
1404 const auto& windowHandles = getWindowHandlesLocked(displayId);
1405 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1406 const WindowInfo& info = *windowHandle->getInfo();
1407
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001408 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001409 continue;
1410 }
1411 if (!info.isSpy()) {
1412 // The first touched non-spy window was found, so return the spy windows touched so far.
1413 return spyWindows;
1414 }
1415 spyWindows.push_back(windowHandle);
1416 }
1417 return spyWindows;
1418}
1419
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001420void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 const char* reason;
1422 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001423 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001424 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001425 ALOGD("Dropped event because policy consumed it.");
1426 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 reason = "inbound event was dropped because the policy consumed it";
1428 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001429 case DropReason::DISABLED:
1430 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 ALOGI("Dropped event because input dispatch is disabled.");
1432 }
1433 reason = "inbound event was dropped because input dispatch is disabled";
1434 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001435 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001436 LOG(INFO) << "Dropping because the current application is not responding and the user "
1437 "has started interacting with a different application: "
1438 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 reason = "inbound event was dropped because the current application is not responding "
1440 "and the user has started interacting with a different application";
1441 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001442 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 ALOGI("Dropped event because it is stale.");
1444 reason = "inbound event was dropped because it is stale";
1445 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001446 case DropReason::NO_POINTER_CAPTURE:
1447 ALOGI("Dropped event because there is no window with Pointer Capture.");
1448 reason = "inbound event was dropped because there is no window with Pointer Capture";
1449 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001450 case DropReason::NOT_DROPPED: {
1451 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001452 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001456 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001457 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001458 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001459 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1460 options.displayId = keyEntry.displayId;
1461 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001463 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001465 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001466 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1467 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001468 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001469 options.displayId = motionEntry.displayId;
1470 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 synthesizeCancelationEventsForAllConnectionsLocked(options);
1472 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001473 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1474 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001475 options.displayId = motionEntry.displayId;
1476 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001477 synthesizeCancelationEventsForAllConnectionsLocked(options);
1478 }
1479 break;
1480 }
Chris Yef59a2f42020-10-16 12:55:26 -07001481 case EventEntry::Type::SENSOR: {
1482 break;
1483 }
arthurhungb89ccb02020-12-30 16:19:01 +08001484 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1485 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001486 break;
1487 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001488 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001489 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001490 case EventEntry::Type::CONFIGURATION_CHANGED:
1491 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001492 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001493 break;
1494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
1496}
1497
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001499 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500}
1501
Prabir Pradhancef936d2021-07-21 16:17:52 +00001502bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001503 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 return false;
1505 }
1506
1507 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001508 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001509 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001510 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1511 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001512 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 return true;
1514}
1515
Prabir Pradhancef936d2021-07-21 16:17:52 +00001516void InputDispatcher::postCommandLocked(Command&& command) {
1517 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518}
1519
1520void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001521 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001522 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001523 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 releaseInboundEventLocked(entry);
1525 }
1526 traceInboundQueueLengthLocked();
1527}
1528
1529void InputDispatcher::releasePendingEventLocked() {
1530 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001532 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534}
1535
Prabir Pradhan24047542023-11-02 17:14:59 +00001536void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001537 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001539 if (DEBUG_DISPATCH_CYCLE) {
1540 ALOGD("Injected inbound event was dropped.");
1541 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548}
1549
1550void InputDispatcher::resetKeyRepeatLocked() {
1551 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001552 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 }
1554}
1555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001557 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558
Michael Wright2e732952014-09-24 13:26:59 -07001559 uint32_t policyFlags = entry->policyFlags &
1560 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001563 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1564 currentTime, entry->deviceId, entry->source,
1565 entry->displayId, policyFlags, entry->action, entry->flags,
1566 entry->keyCode, entry->scanCode, entry->metaState,
1567 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001570 if (mTracer) {
1571 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1572 }
1573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001574 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001576 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577}
1578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001581 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1582 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 // Reset key repeating in case a keyboard device was added or removed or something.
1586 resetKeyRepeatLocked();
1587
1588 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001589 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1590 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001591 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001592 };
1593 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 return true;
1595}
1596
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001597bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1598 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001599 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1600 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1601 entry.deviceId);
1602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
liushenxiang42232912021-05-21 20:24:09 +08001604 // Reset key repeating in case a keyboard device was disabled or enabled.
1605 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1606 resetKeyRepeatLocked();
1607 }
1608
Michael Wrightfb04fd52022-11-24 22:31:11 +00001609 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001610 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001612
1613 // Remove all active pointers from this device
1614 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1615 touchState.removeAllPointersForDevice(entry.deviceId);
1616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 return true;
1618}
1619
Vishnu Nairad321cd2020-08-20 16:40:21 -07001620void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001621 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001622 if (mPendingEvent != nullptr) {
1623 // Move the pending event to the front of the queue. This will give the chance
1624 // for the pending event to get dispatched to the newly focused window
1625 mInboundQueue.push_front(mPendingEvent);
1626 mPendingEvent = nullptr;
1627 }
1628
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001629 std::unique_ptr<FocusEntry> focusEntry =
1630 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1631 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001632
1633 // This event should go to the front of the queue, but behind all other focus events
1634 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001635 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1636 [](const std::shared_ptr<const EventEntry>& event) {
1637 return event->type == EventEntry::Type::FOCUS;
1638 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001639
1640 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001642}
1643
Prabir Pradhan24047542023-11-02 17:14:59 +00001644void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1645 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001646 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1647 if (connection == nullptr) {
1648 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001649 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001650 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001651 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001652 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001653 std::string reason = std::string("reason=").append(entry->reason);
1654 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001655 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001656}
1657
Prabir Pradhan99987712020-11-10 18:43:05 -08001658void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001659 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 dropReason = DropReason::NOT_DROPPED;
1662
Prabir Pradhan99987712020-11-10 18:43:05 -08001663 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001665
1666 if (entry->pointerCaptureRequest.enable) {
1667 // Enable Pointer Capture.
1668 if (haveWindowWithPointerCapture &&
1669 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001670 // This can happen if pointer capture is disabled and re-enabled before we notify the
1671 // app of the state change, so there is no need to notify the app.
1672 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1673 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001674 }
1675 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001676 // This can happen if a window requests capture and immediately releases capture.
1677 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001678 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001679 return;
1680 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001681 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1682 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1683 return;
1684 }
1685
Vishnu Nairc519ff72021-01-21 08:23:08 -08001686 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001687 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1688 mWindowTokenWithPointerCapture = token;
1689 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001690 // Disable Pointer Capture.
1691 // We do not check if the sequence number matches for requests to disable Pointer Capture
1692 // for two reasons:
1693 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1694 // to disable capture with the same sequence number: one generated by
1695 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1696 // Capture being disabled in InputReader.
1697 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1698 // actual Pointer Capture state that affects events being generated by input devices is
1699 // in InputReader.
1700 if (!haveWindowWithPointerCapture) {
1701 // Pointer capture was already forcefully disabled because of focus change.
1702 dropReason = DropReason::NOT_DROPPED;
1703 return;
1704 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001705 token = mWindowTokenWithPointerCapture;
1706 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001707 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001708 setPointerCaptureLocked(false);
1709 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001710 }
1711
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001712 auto connection = getConnectionLocked(token);
1713 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001714 // Window has gone away, clean up Pointer Capture state.
1715 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001716 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001717 setPointerCaptureLocked(false);
1718 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001719 return;
1720 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001721 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001722 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001723
1724 dropReason = DropReason::NOT_DROPPED;
1725}
1726
Prabir Pradhan24047542023-11-02 17:14:59 +00001727void InputDispatcher::dispatchTouchModeChangeLocked(
1728 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001729 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001730 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001731 if (windowHandles.empty()) {
1732 return;
1733 }
1734 const std::vector<InputTarget> inputTargets =
1735 getInputTargetsFromWindowHandlesLocked(windowHandles);
1736 if (inputTargets.empty()) {
1737 return;
1738 }
1739 entry->dispatchInProgress = true;
1740 dispatchEventLocked(currentTime, entry, inputTargets);
1741}
1742
1743std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1744 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1745 std::vector<InputTarget> inputTargets;
1746 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001747 const sp<IBinder>& token = handle->getToken();
1748 if (token == nullptr) {
1749 continue;
1750 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001751 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1752 if (connection == nullptr) {
1753 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001754 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001755 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001756 }
1757 return inputTargets;
1758}
1759
Prabir Pradhan24047542023-11-02 17:14:59 +00001760bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001761 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 if (!entry->dispatchInProgress) {
1764 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1765 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1766 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1767 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001768 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 // We have seen two identical key downs in a row which indicates that the device
1770 // driver is automatically generating key repeats itself. We take note of the
1771 // repeat here, but we disable our own next key repeat timer since it is clear that
1772 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001773 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1774 // Make sure we don't get key down from a different device. If a different
1775 // device Id has same key pressed down, the new device Id will replace the
1776 // current one to hold the key repeat with repeat count reset.
1777 // In the future when got a KEY_UP on the device id, drop it and do not
1778 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1780 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001781 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 } else {
1783 // Not a repeat. Save key down state in case we do see a repeat later.
1784 resetKeyRepeatLocked();
1785 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1786 }
1787 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001788 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1789 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001790 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001791 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001792 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1793 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001794 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 resetKeyRepeatLocked();
1796 }
1797
1798 if (entry->repeatCount == 1) {
1799 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1800 } else {
1801 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1802 }
1803
1804 entry->dispatchInProgress = true;
1805
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001806 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 }
1808
1809 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001810 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001812 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 return false; // wait until next wakeup
1814 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001815 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 entry->interceptKeyWakeupTime = 0;
1817 }
1818
1819 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001820 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001822 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001823 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001824
1825 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1826 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1827 };
1828 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001829 // Poke user activity for keys not passed to user
1830 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 return false; // wait for the command to run
1832 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001833 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001835 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001836 if (*dropReason == DropReason::NOT_DROPPED) {
1837 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 }
1839 }
1840
1841 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001842 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001843 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1845 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001846 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001847 // Poke user activity for undispatched keys
1848 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 return true;
1850 }
1851
1852 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001853 InputEventInjectionResult injectionResult;
1854 sp<WindowInfoHandle> focusedWindow =
1855 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1856 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 return false;
1859 }
1860
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001861 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 return true;
1864 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001865 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1866
1867 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001868 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1869 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001871 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001872 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001874 if (mTracer) {
1875 ensureEventTraced(*entry);
1876 for (const auto& target : inputTargets) {
1877 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1878 }
1879 }
1880
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 // Dispatch the key.
1882 dispatchEventLocked(currentTime, entry, inputTargets);
1883 return true;
1884}
1885
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001886void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001887 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1888 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1889 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1890 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1891 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1892 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1893 entry.metaState, entry.repeatCount, entry.downTime);
1894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895}
1896
Prabir Pradhancef936d2021-07-21 16:17:52 +00001897void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001898 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001899 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001900 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1901 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1902 "source=0x%x, sensorType=%s",
1903 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001904 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001905 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001906 auto command = [this, entry]() REQUIRES(mLock) {
1907 scoped_unlock unlock(mLock);
1908
1909 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001910 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001911 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001912 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1913 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001914 };
1915 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001916}
1917
1918bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001919 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1920 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001921 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001922 }
Chris Yef59a2f42020-10-16 12:55:26 -07001923 { // acquire lock
1924 std::scoped_lock _l(mLock);
1925
1926 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001927 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001928 if (entry->type == EventEntry::Type::SENSOR) {
1929 it = mInboundQueue.erase(it);
1930 releaseInboundEventLocked(entry);
1931 }
1932 }
1933 }
1934 return true;
1935}
1936
Prabir Pradhan24047542023-11-02 17:14:59 +00001937bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1938 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001939 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001940 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001942 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 entry->dispatchInProgress = true;
1944
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001945 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
1947
1948 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001949 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001950 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1952 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 return true;
1954 }
1955
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001956 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
1958 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001959 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001961 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 if (isPointerEvent) {
1963 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001964
1965 if (mDragState &&
1966 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1967 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1968 pilferPointersLocked(mDragState->dragWindow->getToken());
1969 }
1970
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001971 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001972 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001973 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1974 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 } else {
1976 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001977 sp<WindowInfoHandle> focusedWindow =
1978 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1979 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1980 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001981 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1982 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1983 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 return false;
1988 }
1989
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001990 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001991 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 return true;
1993 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001994 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001995 CancelationOptions::Mode mode(
1996 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1997 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001998 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001999 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002000 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 return true;
2002 }
2003
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002004 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002005 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002007 if (mTracer) {
2008 ensureEventTraced(*entry);
2009 for (const auto& target : inputTargets) {
2010 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2011 }
2012 }
2013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 dispatchEventLocked(currentTime, entry, inputTargets);
2016 return true;
2017}
2018
chaviw98318de2021-05-19 16:45:23 -05002019void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002020 bool isExiting, const int32_t rawX,
2021 const int32_t rawY) {
2022 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002023 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002024 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2025 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002026
2027 enqueueInboundEventLocked(std::move(dragEntry));
2028}
2029
Prabir Pradhan24047542023-11-02 17:14:59 +00002030void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2031 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002032 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2033 if (connection == nullptr) {
2034 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002035 }
arthurhungb89ccb02020-12-30 16:19:01 +08002036 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002037 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002038}
2039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002040void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002041 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002042 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002043 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002044 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002045 "metaState=0x%x, buttonState=0x%x,"
2046 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002047 prefix, entry.eventTime, entry.deviceId,
2048 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2049 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2050 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2051 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002053 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002054 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002055 "x=%f, y=%f, pressure=%f, size=%f, "
2056 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2057 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002058 i, entry.pointerProperties[i].id,
2059 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002060 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2061 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2062 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2063 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2064 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2065 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2066 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2067 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2068 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002073void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002074 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002076 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002077 if (DEBUG_DISPATCH_CYCLE) {
2078 ALOGD("dispatchEventToCurrentInputTargets");
2079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002081 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002082
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2084
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002087 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002088 std::shared_ptr<Connection> connection = inputTarget.connection;
2089 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091}
2092
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002093void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002094 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2095 // If the policy decides to close the app, we will get a channel removal event via
2096 // unregisterInputChannel, and will clean up the connection that way. We are already not
2097 // sending new pointers to the connection when it blocked, but focused events will continue to
2098 // pile up.
2099 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002100 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002101 if (connection->status != Connection::Status::NORMAL) {
2102 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002104 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2105 "application not responding");
2106
2107 sp<WindowInfoHandle> windowHandle;
2108 if (!connection->monitor) {
2109 windowHandle = getWindowHandleLocked(connection->getToken());
2110 if (windowHandle == nullptr) {
2111 // The window that is receiving this ANR was removed, so there is no need to generate
2112 // cancellations, because the cancellations would have already been generated when
2113 // the window was removed.
2114 return;
2115 }
2116 }
2117 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118}
2119
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002121 if (DEBUG_FOCUS) {
2122 ALOGD("Resetting ANR timeouts.");
2123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124
2125 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002126 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002127 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128}
2129
Tiger Huang721e26f2018-07-24 22:26:19 +08002130/**
2131 * Get the display id that the given event should go to. If this event specifies a valid display id,
2132 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2133 * Focused display is the display that the user most recently interacted with.
2134 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002135int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002136 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002137 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002138 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2140 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 break;
2142 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002143 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002144 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2145 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 break;
2147 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002148 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002149 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002150 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002151 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002152 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002153 case EventEntry::Type::SENSOR:
2154 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002155 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002156 return ADISPLAY_ID_NONE;
2157 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002158 }
2159 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2160}
2161
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2163 const char* focusedWindowName) {
2164 if (mAnrTracker.empty()) {
2165 // already processed all events that we waited for
2166 mKeyIsWaitingForEventsTimeout = std::nullopt;
2167 return false;
2168 }
2169
2170 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2171 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002172 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002173 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002174 std::chrono::duration_cast<std::chrono::nanoseconds>(
2175 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002176 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002177 return true;
2178 }
2179
2180 // We still have pending events, and already started the timer
2181 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2182 return true; // Still waiting
2183 }
2184
2185 // Waited too long, and some connection still hasn't processed all motions
2186 // Just send the key to the focused window
2187 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2188 focusedWindowName);
2189 mKeyIsWaitingForEventsTimeout = std::nullopt;
2190 return false;
2191}
2192
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002193sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002194 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197
Tiger Huang721e26f2018-07-24 22:26:19 +08002198 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002199 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002200 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002201 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2202
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 // If there is no currently focused window and no focused application
2204 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002205 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2206 ALOGI("Dropping %s event because there is no focused window or focused application in "
2207 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002208 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002209 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 }
2211
Vishnu Nair062a8672021-09-03 16:07:44 -07002212 // Drop key events if requested by input feature
2213 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002214 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002215 }
2216
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002217 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2218 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2219 // start interacting with another application via touch (app switch). This code can be removed
2220 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2221 // an app is expected to have a focused window.
2222 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2223 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2224 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002225 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2226 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2227 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002228 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002229 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002230 ALOGW("Waiting because no window has focus but %s may eventually add a "
2231 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002232 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002233 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002234 outInjectionResult = InputEventInjectionResult::PENDING;
2235 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2237 // Already raised ANR. Drop the event
2238 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002239 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002240 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 } else {
2242 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002243 outInjectionResult = InputEventInjectionResult::PENDING;
2244 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 }
2246 }
2247
2248 // we have a valid, non-null focused window
2249 resetNoFocusedWindowTimeoutLocked();
2250
Prabir Pradhan5735a322022-04-11 17:23:34 +00002251 // Verify targeted injection.
2252 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2253 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002254 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2255 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 }
2257
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002258 if (focusedWindowHandle->getInfo()->inputConfig.test(
2259 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = InputEventInjectionResult::PENDING;
2262 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002263 }
2264
2265 // If the event is a key event, then we must wait for all previous events to
2266 // complete before delivering it because previous events may have the
2267 // side-effect of transferring focus to a different window and we want to
2268 // ensure that the following keys are sent to the new window.
2269 //
2270 // Suppose the user touches a button in a window then immediately presses "A".
2271 // If the button causes a pop-up window to appear then we want to ensure that
2272 // the "A" key is delivered to the new pop-up window. This is because users
2273 // often anticipate pending UI changes when typing on a keyboard.
2274 // To obtain this behavior, we must serialize key events with respect to all
2275 // prior input events.
2276 if (entry.type == EventEntry::Type::KEY) {
2277 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002278 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002279 outInjectionResult = InputEventInjectionResult::PENDING;
2280 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
2283
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002284 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2285 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286}
2287
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002288/**
2289 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2290 * that are currently unresponsive.
2291 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002292std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2293 const std::vector<Monitor>& monitors) const {
2294 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002295 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002296 [](const Monitor& monitor) REQUIRES(mLock) {
2297 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002298 if (!connection->responsive) {
2299 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002300 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002301 return false;
2302 }
2303 return true;
2304 });
2305 return responsiveMonitors;
2306}
2307
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002308std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002309 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002310 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002313 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // For security reasons, we defer updating the touch state until we are sure that
2315 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 const int32_t displayId = entry.displayId;
2317 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002318 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
2320 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002321 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002323 // Copy current touch state into tempTouchState.
2324 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2325 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002326 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002328 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2329 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002330 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002331 }
2332
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002333 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002334
2335 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2336 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2337 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002338 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2339 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002340 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002341 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2342 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002343 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2344 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2345 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002346 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002347
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002348 if (newGesture) {
2349 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002350 }
2351
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002352 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2353 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2354 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002357 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002358 if (wasDown) {
2359 // Started hovering, but the device is already down: reject the hover event
2360 LOG(ERROR) << "Got hover event " << entry.getDescription()
2361 << " but the device is already down " << oldState->dump();
2362 outInjectionResult = InputEventInjectionResult::FAILED;
2363 return {};
2364 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002365 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2366 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002367 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002368 }
2369
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2371 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002372 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002373 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002374 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002375 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2376 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002377 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002378 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002379 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002380
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002381 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002382 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002385 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002386 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002388 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002389 }
2390
Prabir Pradhan5735a322022-04-11 17:23:34 +00002391 // Verify targeted injection.
2392 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2393 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002394 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002395 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002396 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002397 }
2398
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002400 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2402 // New window supports splitting, but we should never split mouse events.
2403 isSplit = !isFromMouse;
2404 } else if (isSplit) {
2405 // New window does not support splitting but we have already split events.
2406 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002407 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2408 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002409 newTouchedWindowHandle = nullptr;
2410 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002411 } else {
2412 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002413 // be delivered to a new window which supports split touch. Pointers from a mouse device
2414 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002415 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002416 }
2417
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002418 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002419 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002421 // Process the foreground window first so that it is the first to receive the event.
2422 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 }
2424
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002425 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002426 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2427 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002428 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002429 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002430 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002431 }
2432
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002433 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002434 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002435 continue;
2436 }
2437
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002438 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002439 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002440 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002441 }
2442
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002443 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002444 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002445
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002446 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2447 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002448 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002449 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002450
2451 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002453 }
2454 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002455 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002456 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002457 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002458 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002459
2460 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002461
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002462 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002463 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2464 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002465 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002466 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002467 isDownOrPointerDown
2468 ? std::make_optional(entry.eventTime)
2469 : std::nullopt);
2470 // If this is the pointer going down and the touched window has a wallpaper
2471 // then also add the touched wallpaper windows so they are locked in for the
2472 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2473 // SCROLL because the wallpaper engine only supports touch events. We would need to
2474 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2475 // handle these events.
2476 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002477 windowHandle->getInfo()->inputConfig.test(
2478 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2479 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2480 if (wallpaper != nullptr) {
2481 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2482 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002483 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002484 if (isSplit) {
2485 wallpaperFlags |= InputTarget::Flags::SPLIT;
2486 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002487 tempTouchState.addOrUpdateWindow(wallpaper,
2488 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002489 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002490 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002491 }
2492 }
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002495
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002496 // If a window is already pilfering some pointers, give it this new pointer as well and
2497 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2498 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002499 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002500 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002501 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002502 // This window is already pilfering some pointers, and this new pointer is also
2503 // going to it. Therefore, take over this pointer and don't give it to anyone
2504 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002505 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002506 }
2507 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002508
2509 // Restrict all pilfered pointers to the pilfering windows.
2510 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 } else {
2512 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2513
2514 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002515 if (!tempTouchState.isDown(entry.deviceId) &&
2516 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002517 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2518 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2519 << " is not down or we previously dropped the pointer down event in "
2520 << "display " << displayId << ": " << entry.getDescription();
2521 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002522 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002523 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 }
2525
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002526 // If the pointer is not currently hovering, then ignore the event.
2527 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2528 const int32_t pointerId = entry.pointerProperties[0].id;
2529 if (oldState == nullptr ||
2530 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2531 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2532 "display "
2533 << displayId << ": " << entry.getDescription();
2534 outInjectionResult = InputEventInjectionResult::FAILED;
2535 return {};
2536 }
2537 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2538 }
2539
arthurhung6d4bed92021-03-17 11:59:33 +08002540 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002541
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002543 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002544 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002545 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002546 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002547 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002548 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002549 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002550 sp<WindowInfoHandle> newTouchedWindowHandle =
2551 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002552
Prabir Pradhan5735a322022-04-11 17:23:34 +00002553 // Verify targeted injection.
2554 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2555 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002556 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002557 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002558 }
2559
Vishnu Nair062a8672021-09-03 16:07:44 -07002560 // Drop touch events if requested by input feature
2561 if (newTouchedWindowHandle != nullptr &&
2562 shouldDropInput(entry, newTouchedWindowHandle)) {
2563 newTouchedWindowHandle = nullptr;
2564 }
2565
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002566 if (newTouchedWindowHandle != nullptr &&
2567 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002568 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002569 oldTouchedWindowHandle->getName().c_str(),
2570 newTouchedWindowHandle->getName().c_str(), displayId);
2571
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002573 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002574 const PointerProperties& pointer = entry.pointerProperties[0];
2575 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002576
2577 const TouchedWindow& touchedWindow =
2578 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002579 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002580 InputTarget::DispatchMode::SLIPPERY_EXIT,
2581 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002582 touchedWindow.getDownTimeInTarget(entry.deviceId),
2583 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584
2585 // Make a slippery entrance into the new window.
2586 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002587 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002590 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002591 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002592 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002595 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 }
2597 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002598 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002599 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002600 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002603 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2604 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002605 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002606 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002607
2608 // Check if the wallpaper window should deliver the corresponding event.
2609 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002610 tempTouchState, entry.deviceId, pointer, targets);
2611 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002612 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
2614 }
Arthur Hung96483742022-11-15 03:30:48 +00002615
2616 // Update the pointerIds for non-splittable when it received pointer down.
2617 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2618 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002619 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002620 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2621 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002622 // Ignore drag window for it should just track one pointer.
2623 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2624 continue;
2625 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002626 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002627 }
2628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 }
2630
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002631 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002632 {
2633 std::vector<TouchedWindow> hoveringWindows =
2634 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2635 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002636 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002637 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2638 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002639 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002640 if (!target) {
2641 continue;
2642 }
2643 // Hardcode to single hovering pointer for now.
2644 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2645 pointerIds.set(entry.pointerProperties[0].id);
2646 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2647 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650
Prabir Pradhan5735a322022-04-11 17:23:34 +00002651 // Ensure that all touched windows are valid for injection.
2652 if (entry.injectionState != nullptr) {
2653 std::string errs;
2654 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002655 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2656 if (err) errs += "\n - " + *err;
2657 }
2658 if (!errs.empty()) {
2659 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002660 "%s:%s",
2661 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002662 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002663 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002664 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002665 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002667 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2668 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002670 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002671 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002672 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002673 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002674 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002675 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002676 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002677 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002678 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2679 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 }
2682 }
2683 }
2684 }
2685
Harry Cuttsb166c002023-05-09 13:06:05 +00002686 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2687 // only want the system UI to handle these gestures.
2688 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2689 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2690 if (isTouchpadNavGesture) {
2691 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2692 }
2693
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002694 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002695 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002696 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002697 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002698 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002699 continue;
2700 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002701 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002702 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002703 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002704 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002705
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002706 // During targeted injection, only allow owned targets to receive events
2707 std::erase_if(targets, [&](const InputTarget& target) {
2708 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2709 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2710 if (err) {
2711 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2712 << ": " << (*err);
2713 return true;
2714 }
2715 return false;
2716 });
2717
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002718 if (targets.empty()) {
2719 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2720 outInjectionResult = InputEventInjectionResult::FAILED;
2721 return {};
2722 }
2723
2724 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2725 // window that is actually receiving the entire gesture.
2726 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002727 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002728 })) {
2729 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2730 << entry.getDescription();
2731 outInjectionResult = InputEventInjectionResult::FAILED;
2732 return {};
2733 }
2734
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002735 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736
Prabir Pradhan502a7252023-12-01 16:11:24 +00002737 // Now that we have generated all of the input targets for this event, reset the dispatch
2738 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002739 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002740 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002741 }
2742
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002743 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002744 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002745 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002746 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002747 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002748 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002749 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002750 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2751 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002752 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2753 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2754 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002757 // Save changes unless the action was scroll in which case the temporary touch
2758 // state was only valid for this one action.
2759 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002760 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002761 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002762 mTouchStatesByDisplay[displayId] = tempTouchState;
2763 } else {
2764 mTouchStatesByDisplay.erase(displayId);
2765 }
2766 }
2767
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002768 if (tempTouchState.windows.empty()) {
2769 mTouchStatesByDisplay.erase(displayId);
2770 }
2771
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002772 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773}
2774
arthurhung6d4bed92021-03-17 11:59:33 +08002775void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002776 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2777 // have an explicit reason to support it.
2778 constexpr bool isStylus = false;
2779
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002780 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002781 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002782 if (dropWindow) {
2783 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002784 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002785 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002786 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002787 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002788 }
2789 mDragState.reset();
2790}
2791
2792void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002793 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002794 return;
2795 }
2796
arthurhung6d4bed92021-03-17 11:59:33 +08002797 if (!mDragState->isStartDrag) {
2798 mDragState->isStartDrag = true;
2799 mDragState->isStylusButtonDownAtStart =
2800 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2801 }
2802
Arthur Hung54745652022-04-20 07:17:41 +00002803 // Find the pointer index by id.
2804 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002805 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002806 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2807 if (pointerProperties.id == mDragState->pointerId) {
2808 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002809 }
Arthur Hung54745652022-04-20 07:17:41 +00002810 }
arthurhung6d4bed92021-03-17 11:59:33 +08002811
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002812 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002813 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002814 }
2815
2816 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2817 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2818 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2819
2820 switch (maskedAction) {
2821 case AMOTION_EVENT_ACTION_MOVE: {
2822 // Handle the special case : stylus button no longer pressed.
2823 bool isStylusButtonDown =
2824 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2825 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2826 finishDragAndDrop(entry.displayId, x, y);
2827 return;
2828 }
2829
2830 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2831 // until we have an explicit reason to support it.
2832 constexpr bool isStylus = false;
2833
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002834 sp<WindowInfoHandle> hoverWindowHandle =
2835 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2836 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002837 // enqueue drag exit if needed.
2838 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2839 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2840 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002841 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002842 y);
2843 }
2844 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2845 }
2846 // enqueue drag location if needed.
2847 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002848 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002849 }
2850 break;
2851 }
2852
2853 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002854 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002855 break;
2856 }
2857 // The drag pointer is up.
2858 [[fallthrough]];
2859 case AMOTION_EVENT_ACTION_UP:
2860 finishDragAndDrop(entry.displayId, x, y);
2861 break;
2862 case AMOTION_EVENT_ACTION_CANCEL: {
2863 ALOGD("Receiving cancel when drag and drop.");
2864 sendDropWindowCommandLocked(nullptr, 0, 0);
2865 mDragState.reset();
2866 break;
2867 }
arthurhungb89ccb02020-12-30 16:19:01 +08002868 }
2869}
2870
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002871std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2872 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002873 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002874 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002875 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2876 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002877 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2878 return {};
2879 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002880 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002881 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002882 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002883 inputTarget.flags = targetFlags;
2884 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2885 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2886 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2887 if (displayInfoIt != mDisplayInfos.end()) {
2888 inputTarget.displayTransform = displayInfoIt->second.transform;
2889 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002890 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002891 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2892 }
2893 return inputTarget;
2894}
2895
chaviw98318de2021-05-19 16:45:23 -05002896void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002897 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002898 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002899 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002900 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 std::vector<InputTarget>::iterator it =
2902 std::find_if(inputTargets.begin(), inputTargets.end(),
2903 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002904 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002905 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002906
chaviw98318de2021-05-19 16:45:23 -05002907 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002908
2909 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002910 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002911 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2912 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002913 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002914 return;
2915 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002916 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002917 it = inputTargets.end() - 1;
2918 }
2919
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002920 if (it->flags != targetFlags) {
2921 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2922 }
2923 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2924 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2925 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2926 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002927}
2928
2929void InputDispatcher::addPointerWindowTargetLocked(
2930 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002931 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2932 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2933 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002934 if (pointerIds.none()) {
2935 for (const auto& target : inputTargets) {
2936 LOG(INFO) << "Target: " << target;
2937 }
2938 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2939 return;
2940 }
2941 std::vector<InputTarget>::iterator it =
2942 std::find_if(inputTargets.begin(), inputTargets.end(),
2943 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002944 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002945 });
2946
2947 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2948 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2949 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2950 // input targets for hovering pointers and for touching pointers.
2951 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2952 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002953 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002954 // Force the code below to create a new input target
2955 it = inputTargets.end();
2956 }
2957
2958 const WindowInfo* windowInfo = windowHandle->getInfo();
2959
2960 if (it == inputTargets.end()) {
2961 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002962 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2963 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002964 if (!target) {
2965 return;
2966 }
2967 inputTargets.push_back(*target);
2968 it = inputTargets.end() - 1;
2969 }
2970
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002971 if (it->dispatchMode != dispatchMode) {
2972 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2973 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2974 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002975 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002976 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2977 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002978 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002979 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002980 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002981 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2982 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002983
chaviw1ff3d1e2020-07-01 15:53:47 -07002984 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985}
2986
Michael Wright3dd60e22019-03-27 22:06:44 +00002987void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002988 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002989 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2990 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002991
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002992 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002993 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002994 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2995 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002996 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2997 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002998 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002999 target.setDefaultPointerTransform(target.displayTransform);
3000 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 }
3002}
3003
Robert Carrc9bf1d32020-04-13 17:21:08 -07003004/**
3005 * Indicate whether one window handle should be considered as obscuring
3006 * another window handle. We only check a few preconditions. Actually
3007 * checking the bounds is left to the caller.
3008 */
chaviw98318de2021-05-19 16:45:23 -05003009static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3010 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003011 // Compare by token so cloned layers aren't counted
3012 if (haveSameToken(windowHandle, otherHandle)) {
3013 return false;
3014 }
3015 auto info = windowHandle->getInfo();
3016 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003017 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003018 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003019 } else if (otherInfo->alpha == 0 &&
3020 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003021 // Those act as if they were invisible, so we don't need to flag them.
3022 // We do want to potentially flag touchable windows even if they have 0
3023 // opacity, since they can consume touches and alter the effects of the
3024 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003025 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003026 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3027 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003028 } else if (info->ownerUid == otherInfo->ownerUid) {
3029 // If ownerUid is the same we don't generate occlusion events as there
3030 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003031 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003032 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003033 return false;
3034 } else if (otherInfo->displayId != info->displayId) {
3035 return false;
3036 }
3037 return true;
3038}
3039
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003040/**
3041 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3042 * untrusted, one should check:
3043 *
3044 * 1. If result.hasBlockingOcclusion is true.
3045 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3046 * BLOCK_UNTRUSTED.
3047 *
3048 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3049 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3050 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3051 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3052 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3053 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3054 *
3055 * If neither of those is true, then it means the touch can be allowed.
3056 */
3057InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003058 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3059 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003060 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003061 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 TouchOcclusionInfo info;
3063 info.hasBlockingOcclusion = false;
3064 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003065 info.obscuringUid = gui::Uid::INVALID;
3066 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003067 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003068 if (windowHandle == otherHandle) {
3069 break; // All future windows are below us. Exit early.
3070 }
chaviw98318de2021-05-19 16:45:23 -05003071 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003072 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3073 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003074 if (DEBUG_TOUCH_OCCLUSION) {
3075 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003076 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003077 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003078 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3079 // we perform the checks below to see if the touch can be propagated or not based on the
3080 // window's touch occlusion mode
3081 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3082 info.hasBlockingOcclusion = true;
3083 info.obscuringUid = otherInfo->ownerUid;
3084 info.obscuringPackage = otherInfo->packageName;
3085 break;
3086 }
3087 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003088 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003089 float opacity =
3090 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3091 // Given windows A and B:
3092 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3093 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3094 opacityByUid[uid] = opacity;
3095 if (opacity > info.obscuringOpacity) {
3096 info.obscuringOpacity = opacity;
3097 info.obscuringUid = uid;
3098 info.obscuringPackage = otherInfo->packageName;
3099 }
3100 }
3101 }
3102 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003103 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003104 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003105 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003106 return info;
3107}
3108
chaviw98318de2021-05-19 16:45:23 -05003109std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003110 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003111 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003112 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3113 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3114 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003115 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003116 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003117 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3118 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003119 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3120 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3121 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003122 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003123}
3124
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003125bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3126 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003127 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3128 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003129 return false;
3130 }
3131 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003132 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003133 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003134 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003135 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3136 return false;
3137 }
3138 return true;
3139}
3140
chaviw98318de2021-05-19 16:45:23 -05003141bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003144 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3145 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003146 if (windowHandle == otherHandle) {
3147 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
chaviw98318de2021-05-19 16:45:23 -05003149 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003150 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003151 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 return true;
3153 }
3154 }
3155 return false;
3156}
3157
chaviw98318de2021-05-19 16:45:23 -05003158bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003159 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003160 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3161 const WindowInfo* windowInfo = windowHandle->getInfo();
3162 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003163 if (windowHandle == otherHandle) {
3164 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003165 }
chaviw98318de2021-05-19 16:45:23 -05003166 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003167 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003168 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003169 return true;
3170 }
3171 }
3172 return false;
3173}
3174
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003175std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003176 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003177 if (applicationHandle != nullptr) {
3178 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003179 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 } else {
3181 return applicationHandle->getName();
3182 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003183 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003184 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003186 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 }
3188}
3189
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003190void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003191 if (!isUserActivityEvent(eventEntry)) {
3192 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003193 return;
3194 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003195
3196 const int32_t eventType = getUserActivityEventType(eventEntry);
3197 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3198 // Note that we're directly getting the time diff between the current event and the previous
3199 // event. This is assuming that the first user event always happens at a timestamp that is
3200 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3201 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3202 // value than the potential first user activity event time, so this is ok.
3203 std::chrono::nanoseconds timeSinceLastEvent =
3204 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3205 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3206 return;
3207 }
3208 }
3209
Tiger Huang721e26f2018-07-24 22:26:19 +08003210 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003211 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003212 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003213 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003214 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003215 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003216 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218 }
3219
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003221 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003222 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3223 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 return;
3225 }
Josep del Riob3981622023-04-18 15:49:45 +00003226 if (windowDisablingUserActivityInfo != nullptr) {
3227 if (DEBUG_DISPATCH_CYCLE) {
3228 ALOGD("Not poking user activity: disabled by window '%s'.",
3229 windowDisablingUserActivityInfo->name.c_str());
3230 }
3231 return;
3232 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003235 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003236 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3237 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 return;
3239 }
Josep del Riob3981622023-04-18 15:49:45 +00003240 // If the key code is unknown, we don't consider it user activity
3241 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3242 return;
3243 }
3244 // Don't inhibit events that were intercepted or are not passed to
3245 // the apps, like system shortcuts
3246 if (windowDisablingUserActivityInfo != nullptr &&
3247 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3248 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3249 if (DEBUG_DISPATCH_CYCLE) {
3250 ALOGD("Not poking user activity: disabled by window '%s'.",
3251 windowDisablingUserActivityInfo->name.c_str());
3252 }
3253 return;
3254 }
3255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003258 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003259 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003260 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003261 break;
3262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 }
3264
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003265 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003266 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3267 REQUIRES(mLock) {
3268 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003269 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003270 };
3271 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272}
3273
3274void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003275 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003276 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003277 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003278 ATRACE_NAME_IF(ATRACE_ENABLED(),
3279 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3280 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003281 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003283 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003285 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003286 inputTarget.getPointerInfoString().c_str());
3287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288
3289 // Skip this event if the connection status is not normal.
3290 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003291 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003292 if (DEBUG_DISPATCH_CYCLE) {
3293 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003294 connection->getInputChannelName().c_str(),
3295 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 return;
3298 }
3299
3300 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003301 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003302 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003303 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003304 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003306 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003307 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003308 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3309 logDispatchStateLocked();
3310 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3311 "target on connection "
3312 << connection->getInputChannelName() << " for "
3313 << originalMotionEntry.getDescription();
3314 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003316 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003317 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 if (!splitMotionEntry) {
3319 return; // split event was dropped
3320 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003321 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3322 std::string reason = std::string("reason=pointer cancel on split window");
3323 android_log_event_list(LOGTAG_INPUT_CANCEL)
3324 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3325 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003326 if (DEBUG_FOCUS) {
3327 ALOGD("channel '%s' ~ Split motion event.",
3328 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003329 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003330 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003331 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3332 std::move(splitMotionEntry),
3333 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 return;
3335 }
3336 }
3337
3338 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3340 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341}
3342
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003343void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3344 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3345 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003346 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003347 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3348 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003349 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003350
hongzuo liu95785e22022-09-06 02:51:35 +00003351 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003353 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
3355 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003356 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 startDispatchCycleLocked(currentTime, connection);
3358 }
3359}
3360
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003361void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003362 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003363 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003364 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3365 eventEntry->type == EventEntry::Type::MOTION;
3366 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3367 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3368 << inputTarget << " connection: " << connection->getInputChannelName()
3369 << " entry: " << eventEntry->getDescription();
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 // This is a new event.
3372 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003373 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003374 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3375 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003377 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3378 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003379 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003381 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003382 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003383 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3384 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003385 LOG(WARNING) << "channel " << connection->getInputChannelName()
3386 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 return; // skip the inconsistent event
3388 }
3389 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003392 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003393 std::shared_ptr<const MotionEntry> resolvedMotion =
3394 std::static_pointer_cast<const MotionEntry>(eventEntry);
3395 {
3396 // Determine the resolved motion entry.
3397 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3398 int32_t resolvedAction = motionEntry.action;
3399 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003401 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003402 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003403 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003404 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003405 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003406 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003407 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003408 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003409 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003410 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3411 }
3412 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3413 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3414 motionEntry.displayId)) {
3415 if (DEBUG_DISPATCH_CYCLE) {
3416 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3417 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3418 "enter event";
3419 }
3420 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3421 }
3422
3423 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3424 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3425 }
3426 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3427 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3428 }
3429 if (dispatchEntry->targetFlags.test(
3430 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3431 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3432 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003433 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3434 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3435 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003436
3437 dispatchEntry->resolvedFlags = resolvedFlags;
3438 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003439 std::optional<std::vector<PointerProperties>> usingProperties;
3440 std::optional<std::vector<PointerCoords>> usingCoords;
3441 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3442 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3443 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3444 // the dispatcher, and therefore the coordinates of this event are currently
3445 // incorrect. These events should use the coordinates of the last dispatched
3446 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3447 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3448 std::optional<std::pair<std::vector<PointerProperties>,
3449 std::vector<PointerCoords>>>
3450 pointerInfo =
3451 connection->inputState.getPointersOfLastEvent(motionEntry,
3452 hovering);
3453 if (pointerInfo) {
3454 usingProperties = pointerInfo->first;
3455 usingCoords = pointerInfo->second;
3456 }
3457 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003458 // Generate a new MotionEntry with a new eventId using the resolved action and
3459 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003460 resolvedMotion = std::make_shared<
3461 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3462 motionEntry.eventTime, motionEntry.deviceId,
3463 motionEntry.source, motionEntry.displayId,
3464 motionEntry.policyFlags, resolvedAction,
3465 motionEntry.actionButton, resolvedFlags,
3466 motionEntry.metaState, motionEntry.buttonState,
3467 motionEntry.classification, motionEntry.edgeFlags,
3468 motionEntry.xPrecision, motionEntry.yPrecision,
3469 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3470 motionEntry.downTime,
3471 usingProperties.value_or(motionEntry.pointerProperties),
3472 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003473 if (ATRACE_ENABLED()) {
3474 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3475 ") to MotionEvent(id=0x%" PRIx32 ").",
3476 motionEntry.id, resolvedMotion->id);
3477 ATRACE_NAME(message.c_str());
3478 }
3479
3480 // Set the resolved motion entry in the DispatchEntry.
3481 dispatchEntry->eventEntry = resolvedMotion;
3482 eventEntry = resolvedMotion;
3483 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003486 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3487 // devices being active at the same time in the same window, so if a new device is
3488 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003489 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003490 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003491 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003492 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003493 << connection->getInputChannelName() << " with event "
3494 << cancelEvent->getDescription();
3495 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003496 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003497 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003498
3499 // Send these cancel events to the queue before sending the event from the new
3500 // device.
3501 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3502 }
3503
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003504 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003506 LOG(WARNING) << "channel " << connection->getInputChannelName()
3507 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508 return; // skip the inconsistent event
3509 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003510 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003511 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003512 // Skip reporting pointer down outside focus to the policy.
3513 break;
3514 }
3515
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003516 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003517 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518
3519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003521 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003522 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003523 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3524 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003525 break;
3526 }
Chris Yef59a2f42020-10-16 12:55:26 -07003527 case EventEntry::Type::SENSOR: {
3528 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3529 break;
3530 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003531 case EventEntry::Type::CONFIGURATION_CHANGED:
3532 case EventEntry::Type::DEVICE_RESET: {
3533 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003534 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003535 break;
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
3538
3539 // Remember that we are waiting for this dispatch to complete.
3540 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003541 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543
3544 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003545 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003546 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003547}
3548
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003549/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003550 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003552 * The first role is to log input interaction with windows, which helps determine what the user was
3553 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3554 * that user started interacting with launcher window, as well as any other window that received
3555 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3556 * when the set of tokens that received the event changes. It is not logged again as long as the
3557 * user is interacting with the same windows.
3558 *
3559 * The second role is to track input device activity for metrics collection. For each input event,
3560 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3561 * input_interaction logs, the device interaction is reported even when the set of interaction
3562 * tokens do not change.
3563 *
3564 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3565 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003566 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003567void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3568 const std::vector<InputTarget>& targets) {
3569 int32_t deviceId;
3570 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003571 // Skip ACTION_UP events, and all events other than keys and motions
3572 if (entry.type == EventEntry::Type::KEY) {
3573 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3574 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3575 return;
3576 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003577 deviceId = keyEntry.deviceId;
3578 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003579 } else if (entry.type == EventEntry::Type::MOTION) {
3580 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3581 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003582 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3583 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003584 return;
3585 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003586 deviceId = motionEntry.deviceId;
3587 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003588 } else {
3589 return; // Not a key or a motion
3590 }
3591
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003592 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003593 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003594 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003595 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003596 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003597 continue; // Skip windows that receive ACTION_OUTSIDE
3598 }
3599
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003600 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003601 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003602 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003603 if (target.windowHandle) {
3604 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3605 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003606 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003607
3608 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3609 REQUIRES(mLock) {
3610 scoped_unlock unlock(mLock);
3611 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3612 };
3613 postCommandLocked(std::move(command));
3614
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003615 if (newConnectionTokens == mInteractionConnectionTokens) {
3616 return; // no change
3617 }
3618 mInteractionConnectionTokens = newConnectionTokens;
3619
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003620 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003621 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003622 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003623 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003624 std::string message = "Interaction with: " + targetList;
3625 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003626 message += "<none>";
3627 }
3628 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3629}
3630
chaviwfd6d3512019-03-25 13:23:49 -07003631void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003632 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003633 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003634 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3635 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003636 return;
3637 }
3638
Vishnu Nairc519ff72021-01-21 08:23:08 -08003639 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003640 if (focusedToken == token) {
3641 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003642 return;
3643 }
3644
Prabir Pradhancef936d2021-07-21 16:17:52 +00003645 auto command = [this, token]() REQUIRES(mLock) {
3646 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003647 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003648 };
3649 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650}
3651
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003652status_t InputDispatcher::publishMotionEvent(Connection& connection,
3653 DispatchEntry& dispatchEntry) const {
3654 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3655 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3656
3657 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003658 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003659
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003660 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003661 // Set the X and Y offset and X and Y scale depending on the input source.
3662 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003663 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003664 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3665 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003666 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003667 scaledCoords[i] = motionEntry.pointerCoords[i];
3668 // Don't apply window scale here since we don't want scale to affect raw
3669 // coordinates. The scale will be sent back to the client and applied
3670 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003671 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003672 }
3673 usingCoords = scaledCoords;
3674 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003675 }
3676
3677 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3678
3679 // Publish the motion event.
3680 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003681 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3682 motionEntry.source, motionEntry.displayId, std::move(hmac),
3683 motionEntry.action, motionEntry.actionButton,
3684 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3685 motionEntry.metaState, motionEntry.buttonState,
3686 motionEntry.classification, dispatchEntry.transform,
3687 motionEntry.xPrecision, motionEntry.yPrecision,
3688 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3689 dispatchEntry.rawTransform, motionEntry.downTime,
3690 motionEntry.eventTime, motionEntry.getPointerCount(),
3691 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003692}
3693
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003695 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003696 ATRACE_NAME_IF(ATRACE_ENABLED(),
3697 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3698 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003699 if (DEBUG_DISPATCH_CYCLE) {
3700 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003703 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003704 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003706 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003707 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708
3709 // Publish the event.
3710 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003711 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3712 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003713 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003714 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3715 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003716 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003717 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3718 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003722 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003723 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3724 keyEntry.deviceId, keyEntry.source,
3725 keyEntry.displayId, std::move(hmac),
3726 keyEntry.action, dispatchEntry->resolvedFlags,
3727 keyEntry.keyCode, keyEntry.scanCode,
3728 keyEntry.metaState, keyEntry.repeatCount,
3729 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003730 if (mTracer) {
3731 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3732 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
3735
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003736 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003737 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003738 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3739 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003740 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003741 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003742 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003743 if (mTracer) {
3744 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3745 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003746 break;
3747 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003748
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003749 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003750 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003751 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003752 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003753 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003754 break;
3755 }
3756
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003757 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3758 const TouchModeEntry& touchModeEntry =
3759 static_cast<const TouchModeEntry&>(eventEntry);
3760 status = connection->inputPublisher
3761 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3762 touchModeEntry.inTouchMode);
3763
3764 break;
3765 }
3766
Prabir Pradhan99987712020-11-10 18:43:05 -08003767 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3768 const auto& captureEntry =
3769 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3770 status = connection->inputPublisher
3771 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003772 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003773 break;
3774 }
3775
arthurhungb89ccb02020-12-30 16:19:01 +08003776 case EventEntry::Type::DRAG: {
3777 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3778 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3779 dragEntry.id, dragEntry.x,
3780 dragEntry.y,
3781 dragEntry.isExiting);
3782 break;
3783 }
3784
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003785 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003786 case EventEntry::Type::DEVICE_RESET:
3787 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003788 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003789 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003790 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 }
3793
3794 // Check the result.
3795 if (status) {
3796 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003797 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003799 "This is unexpected because the wait queue is empty, so the pipe "
3800 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003801 "event to it, status=%s(%d)",
3802 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3803 status);
Harry Cutts33476232023-01-30 19:57:29 +00003804 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 } else {
3806 // Pipe is full and we are waiting for the app to finish process some events
3807 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003808 if (DEBUG_DISPATCH_CYCLE) {
3809 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3810 "waiting for the application to catch up",
3811 connection->getInputChannelName().c_str());
3812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814 } else {
3815 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003816 "status=%s(%d)",
3817 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3818 status);
Harry Cutts33476232023-01-30 19:57:29 +00003819 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821 return;
3822 }
3823
3824 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003825 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3826 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3827 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003828 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003829 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003830 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003831 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003832 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
3834}
3835
chaviw09c8d2d2020-08-24 15:48:26 -07003836std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3837 size_t size;
3838 switch (event.type) {
3839 case VerifiedInputEvent::Type::KEY: {
3840 size = sizeof(VerifiedKeyEvent);
3841 break;
3842 }
3843 case VerifiedInputEvent::Type::MOTION: {
3844 size = sizeof(VerifiedMotionEvent);
3845 break;
3846 }
3847 }
3848 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3849 return mHmacKeyManager.sign(start, size);
3850}
3851
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003852const std::array<uint8_t, 32> InputDispatcher::getSignature(
3853 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003854 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003855 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003856 // Only sign events up and down events as the purely move events
3857 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003858 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003859 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003860
3861 VerifiedMotionEvent verifiedEvent =
3862 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3863 verifiedEvent.actionMasked = actionMasked;
3864 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3865 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003866}
3867
3868const std::array<uint8_t, 32> InputDispatcher::getSignature(
3869 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3870 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3871 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003872 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003873}
3874
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003876 const std::shared_ptr<Connection>& connection,
3877 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003878 if (DEBUG_DISPATCH_CYCLE) {
3879 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3880 connection->getInputChannelName().c_str(), seq, toString(handled));
3881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003883 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 return;
3885 }
3886
3887 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003888 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3889 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3890 };
3891 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892}
3893
3894void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003895 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003897 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003898 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3899 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
3902 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003903 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003904 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003905 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003906 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907
3908 // The connection appears to be unrecoverably broken.
3909 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003910 if (connection->status == Connection::Status::NORMAL) {
3911 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
3913 if (notify) {
3914 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003915 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3916 connection->getInputChannelName().c_str());
3917
3918 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003919 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003920 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003921 };
3922 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
3924 }
3925}
3926
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003927void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003928 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003929 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003930 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 }
3932}
3933
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003934void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003936 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938}
3939
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003940int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3941 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003942 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003943 if (connection == nullptr) {
3944 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3945 connectionToken.get(), events);
3946 return 0; // remove the callback
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003949 bool notify;
3950 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3951 if (!(events & ALOOPER_EVENT_INPUT)) {
3952 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3953 "events=0x%x",
3954 connection->getInputChannelName().c_str(), events);
3955 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
3957
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003958 nsecs_t currentTime = now();
3959 bool gotOne = false;
3960 status_t status = OK;
3961 for (;;) {
3962 Result<InputPublisher::ConsumerResponse> result =
3963 connection->inputPublisher.receiveConsumerResponse();
3964 if (!result.ok()) {
3965 status = result.error().code();
3966 break;
3967 }
3968
3969 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3970 const InputPublisher::Finished& finish =
3971 std::get<InputPublisher::Finished>(*result);
3972 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3973 finish.consumeTime);
3974 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003975 if (shouldReportMetricsForConnection(*connection)) {
3976 const InputPublisher::Timeline& timeline =
3977 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003978 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3979 connection->getToken(),
3980 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003981 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003982 }
3983 gotOne = true;
3984 }
3985 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003986 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003987 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 return 1;
3989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
3991
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003992 notify = status != DEAD_OBJECT || !connection->monitor;
3993 if (notify) {
3994 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3995 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3996 status);
3997 }
3998 } else {
3999 // Monitor channels are never explicitly unregistered.
4000 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004001 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004002 notify = !connection->monitor && stillHaveWindowHandle;
4003 if (notify) {
4004 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4005 connection->getInputChannelName().c_str(), events);
4006 }
4007 }
4008
4009 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004010 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004011 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012}
4013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004014void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004016 // Cancel windows (i.e. non-monitors).
4017 // A channel must have at least one window to receive any input. If a window was removed, the
4018 // event streams directed to the window will already have been canceled during window removal.
4019 // So there is no need to generate cancellations for connections without any windows.
4020 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4021 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4022 // through a non-touched window if there are more than one window for an input channel.
4023 if (cancelPointers) {
4024 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4025 if (options.displayId.has_value() && options.displayId != displayId) {
4026 continue;
4027 }
4028 for (const auto& touchedWindow : touchState.windows) {
4029 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4030 }
4031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004033 // Follow up by generating cancellations for all windows, because we don't explicitly track
4034 // the windows that have an ongoing focus event stream.
4035 if (cancelNonPointers) {
4036 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4037 for (const auto& windowHandle : handles) {
4038 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4039 }
4040 }
4041 }
4042
4043 // Cancel monitors.
4044 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045}
4046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004048 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004049 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004050 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004051 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4052 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004053 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004054 }
4055}
4056
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004057void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4058 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4059 const std::shared_ptr<Connection>& connection) {
4060 if (windowHandle == nullptr) {
4061 LOG(FATAL) << __func__ << ": Window handle must not be null";
4062 }
4063 if (connection) {
4064 // The connection can be optionally provided to avoid multiple lookups.
4065 if (windowHandle->getToken() != connection->getToken()) {
4066 LOG(FATAL) << __func__
4067 << ": Wrong connection provided for window: " << windowHandle->getName();
4068 }
4069 }
4070
4071 std::shared_ptr<Connection> resolvedConnection =
4072 connection ? connection : getConnectionLocked(windowHandle->getToken());
4073 if (!resolvedConnection) {
4074 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4075 return;
4076 }
4077 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4078}
4079
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004081 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4082 const sp<WindowInfoHandle>& window) {
4083 if (!connection->monitor && window == nullptr) {
4084 LOG(FATAL) << __func__
4085 << ": Cannot send event to non-monitor channel without a window - channel: "
4086 << connection->getInputChannelName();
4087 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004088 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 return;
4090 }
4091
4092 nsecs_t currentTime = now();
4093
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004094 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004095 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004097 if (cancelationEvents.empty()) {
4098 return;
4099 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004100
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004101 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4102 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004103 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004104 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004105 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004106 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004107
Arthur Hungb3307ee2021-10-14 10:57:37 +00004108 std::string reason = std::string("reason=").append(options.reason);
4109 android_log_event_list(LOGTAG_INPUT_CANCEL)
4110 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4111
hongzuo liu95785e22022-09-06 02:51:35 +00004112 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004113 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004114 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004115 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004116
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004117 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004119 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004120
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004121 switch (cancelationEventEntry->type) {
4122 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004123 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004124 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004125 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4126 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004127 } else {
4128 targets.emplace_back(fallbackTarget);
4129 }
4130 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004131 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004133 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004134 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004135 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004136 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004137 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004138 pointerIndex++) {
4139 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4140 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004141 if (mDragState && mDragState->dragWindow->getToken() == token &&
4142 pointerIds.test(mDragState->pointerId)) {
4143 LOG(INFO) << __func__
4144 << ": Canceling drag and drop because the pointers for the drag "
4145 "window are being canceled.";
4146 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4147 mDragState.reset();
4148 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004149 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4150 ftl::Flags<InputTarget::Flags>(), pointerIds,
4151 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004152 } else {
4153 targets.emplace_back(fallbackTarget);
4154 const auto it = mDisplayInfos.find(motionEntry.displayId);
4155 if (it != mDisplayInfos.end()) {
4156 targets.back().displayTransform = it->second.transform;
4157 targets.back().setDefaultPointerTransform(it->second.transform);
4158 }
4159 }
4160 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004163 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004164 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004165 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4166 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004167 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004168 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004169 break;
4170 }
4171 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004172 case EventEntry::Type::DEVICE_RESET:
4173 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004174 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004175 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004176 break;
4177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
4179
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004180 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004181 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004183
hongzuo liu95785e22022-09-06 02:51:35 +00004184 // If the outbound queue was previously empty, start the dispatch cycle going.
4185 if (wasEmpty && !connection->outboundQueue.empty()) {
4186 startDispatchCycleLocked(currentTime, connection);
4187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188}
4189
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004191 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004192 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004193 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004194 return;
4195 }
4196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004198 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004199
4200 if (downEvents.empty()) {
4201 return;
4202 }
4203
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004204 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4206 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004207 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004208
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004209 const auto [_, touchedWindowState, displayId] =
4210 findTouchStateWindowAndDisplayLocked(connection->getToken());
4211 if (touchedWindowState == nullptr) {
4212 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4213 }
4214 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004215
hongzuo liu95785e22022-09-06 02:51:35 +00004216 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004218 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004219 switch (downEventEntry->type) {
4220 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004221 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4222 if (windowHandle != nullptr) {
4223 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004224 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004225 pointerIndex++) {
4226 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4227 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004228 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4229 targetFlags, pointerIds, motionEntry.downTime,
4230 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004231 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004232 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004233 const auto it = mDisplayInfos.find(motionEntry.displayId);
4234 if (it != mDisplayInfos.end()) {
4235 targets.back().displayTransform = it->second.transform;
4236 targets.back().setDefaultPointerTransform(it->second.transform);
4237 }
4238 }
4239 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004240 break;
4241 }
4242
4243 case EventEntry::Type::KEY:
4244 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004245 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004247 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004248 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004249 case EventEntry::Type::SENSOR:
4250 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004251 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004252 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004253 break;
4254 }
4255 }
4256
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004257 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004258 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004259 }
4260
hongzuo liu95785e22022-09-06 02:51:35 +00004261 // If the outbound queue was previously empty, start the dispatch cycle going.
4262 if (wasEmpty && !connection->outboundQueue.empty()) {
4263 startDispatchCycleLocked(downTime, connection);
4264 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004265}
4266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004268 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4269 nsecs_t splitDownTime) {
4270 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
4272 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004273 std::vector<PointerProperties> splitPointerProperties;
4274 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004276 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 uint32_t splitPointerCount = 0;
4278
4279 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004282 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004284 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004286 splitPointerProperties.push_back(pointerProperties);
4287 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 splitPointerCount += 1;
4289 }
4290 }
4291
4292 if (splitPointerCount != pointerIds.count()) {
4293 // This is bad. We are missing some of the pointers that we expected to deliver.
4294 // Most likely this indicates that we received an ACTION_MOVE events that has
4295 // different pointer ids than we expected based on the previous ACTION_DOWN
4296 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4297 // in this way.
4298 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004299 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004300 "a broken sequence of pointer ids from the input device: %s",
4301 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004302 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 }
4304
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004305 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4308 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004309 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004311 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004313 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 if (pointerIds.count() == 1) {
4315 // The first/last pointer went down/up.
4316 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004318 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4319 ? AMOTION_EVENT_ACTION_CANCEL
4320 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 } else {
4322 // A secondary pointer went down/up.
4323 uint32_t splitPointerIndex = 0;
4324 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4325 splitPointerIndex += 1;
4326 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 action = maskedAction |
4328 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 }
4330 } else {
4331 // An unrelated pointer changed.
4332 action = AMOTION_EVENT_ACTION_MOVE;
4333 }
4334 }
4335
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004336 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4337 logDispatchStateLocked();
4338 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4339 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4340 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004341 }
4342
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004343 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004344 ATRACE_NAME_IF(ATRACE_ENABLED(),
4345 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4346 ").",
4347 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004349 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4350 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004351 originalMotionEntry.deviceId, originalMotionEntry.source,
4352 originalMotionEntry.displayId,
4353 originalMotionEntry.policyFlags, action,
4354 originalMotionEntry.actionButton,
4355 originalMotionEntry.flags, originalMotionEntry.metaState,
4356 originalMotionEntry.buttonState,
4357 originalMotionEntry.classification,
4358 originalMotionEntry.edgeFlags,
4359 originalMotionEntry.xPrecision,
4360 originalMotionEntry.yPrecision,
4361 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004362 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004363 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 return splitMotionEntry;
4366}
4367
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004368void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4369 std::scoped_lock _l(mLock);
4370 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4371}
4372
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004374 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004375 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
Antonio Kantekf16f2832021-09-28 04:39:20 +00004378 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004380 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004383 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004384 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 } // release lock
4386
4387 if (needWake) {
4388 mLooper->wake();
4389 }
4390}
4391
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004392void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004393 ALOGD_IF(debugInboundEventDetails(),
4394 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4395 ", deviceId=%d, source=%s, displayId=%" PRId32
4396 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4397 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004398 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4399 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4400 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004401 Result<void> keyCheck = validateKeyEvent(args.action);
4402 if (!keyCheck.ok()) {
4403 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 return;
4405 }
4406
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004407 uint32_t policyFlags = args.policyFlags;
4408 int32_t flags = args.flags;
4409 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004410 // InputDispatcher tracks and generates key repeats on behalf of
4411 // whatever notifies it, so repeatCount should always be set to 0
4412 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4414 policyFlags |= POLICY_FLAG_VIRTUAL;
4415 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 if (policyFlags & POLICY_FLAG_FUNCTION) {
4418 metaState |= AMETA_FUNCTION_ON;
4419 }
4420
4421 policyFlags |= POLICY_FLAG_TRUSTED;
4422
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004423 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004425 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4426 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4427 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Michael Wright2b3c3302018-03-02 17:19:13 +00004429 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004430 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004431 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4432 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
Antonio Kantekf16f2832021-09-28 04:39:20 +00004436 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 { // acquire lock
4438 mLock.lock();
4439
4440 if (shouldSendKeyToInputFilterLocked(args)) {
4441 mLock.unlock();
4442
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004443 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004444 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 return; // event was consumed by the filter
4446 }
4447
4448 mLock.lock();
4449 }
4450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004452 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4453 args.deviceId, args.source, args.displayId, policyFlags,
4454 args.action, flags, keyCode, args.scanCode, metaState,
4455 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004456 if (mTracer) {
4457 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004460 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 mLock.unlock();
4462 } // release lock
4463
4464 if (needWake) {
4465 mLooper->wake();
4466 }
4467}
4468
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004469bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 return mInputFilterEnabled;
4471}
4472
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004473void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004474 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004475 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004477 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004478 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4479 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004480 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4481 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4482 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4483 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4484 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004485 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004486 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4487 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488 i, args.pointerProperties[i].id,
4489 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4490 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4491 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4492 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4493 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4494 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4495 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4496 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4497 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4498 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004501
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004502 Result<void> motionCheck =
4503 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4504 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004505 if (!motionCheck.ok()) {
4506 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4507 return;
4508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004510 if (DEBUG_VERIFY_EVENTS) {
4511 auto [it, _] =
4512 mVerifiersByDisplay.try_emplace(args.displayId,
4513 StringPrintf("display %" PRId32, args.displayId));
4514 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004515 it->second.processMovement(args.deviceId, args.source, args.action,
4516 args.getPointerCount(), args.pointerProperties.data(),
4517 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004518 if (!result.ok()) {
4519 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4520 }
4521 }
4522
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004523 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004525
4526 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004527 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4528 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004529 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4530 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533
Antonio Kantekf16f2832021-09-28 04:39:20 +00004534 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 { // acquire lock
4536 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004537 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4538 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4539 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004540 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004541 if (touchStateIt != mTouchStatesByDisplay.end()) {
4542 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004543 if (touchState.hasTouchingPointers(args.deviceId) ||
4544 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004545 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4546 }
4547 }
4548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
4550 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004551 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004552 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004553 displayTransform = it->second.transform;
4554 }
4555
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 mLock.unlock();
4557
4558 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004559 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4560 args.action, args.actionButton, args.flags, args.edgeFlags,
4561 args.metaState, args.buttonState, args.classification,
4562 displayTransform, args.xPrecision, args.yPrecision,
4563 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004564 args.downTime, args.eventTime, args.getPointerCount(),
4565 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566
4567 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004568 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 return; // event was consumed by the filter
4570 }
4571
4572 mLock.lock();
4573 }
4574
4575 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004576 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004577 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4578 args.deviceId, args.source, args.displayId,
4579 policyFlags, args.action, args.actionButton,
4580 args.flags, args.metaState, args.buttonState,
4581 args.classification, args.edgeFlags, args.xPrecision,
4582 args.yPrecision, args.xCursorPosition,
4583 args.yCursorPosition, args.downTime,
4584 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004585 if (mTracer) {
4586 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004589 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4590 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004591 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004592 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004593 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4594 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4595 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004596 }
4597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004598 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 mLock.unlock();
4600 } // release lock
4601
4602 if (needWake) {
4603 mLooper->wake();
4604 }
4605}
4606
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004607void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004608 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004609 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4610 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611 args.id, args.eventTime, args.deviceId, args.source,
4612 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004613 }
Chris Yef59a2f42020-10-16 12:55:26 -07004614
Antonio Kantekf16f2832021-09-28 04:39:20 +00004615 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004616 { // acquire lock
4617 mLock.lock();
4618
4619 // Just enqueue a new sensor event.
4620 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004621 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4622 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4623 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004624
4625 needWake = enqueueInboundEventLocked(std::move(newEntry));
4626 mLock.unlock();
4627 } // release lock
4628
4629 if (needWake) {
4630 mLooper->wake();
4631 }
4632}
4633
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004634void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004635 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004636 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4637 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004638 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004639 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004640}
4641
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004642bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004643 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644}
4645
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004647 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004648 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4649 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004653 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004655 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656}
4657
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004658void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004659 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004660 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4661 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
Antonio Kantekf16f2832021-09-28 04:39:20 +00004664 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004666 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004668 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004669 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004670 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004671
4672 for (auto& [_, verifier] : mVerifiersByDisplay) {
4673 verifier.resetDevice(args.deviceId);
4674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 } // release lock
4676
4677 if (needWake) {
4678 mLooper->wake();
4679 }
4680}
4681
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004682void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004683 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004684 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4685 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004686 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004687
Antonio Kantekf16f2832021-09-28 04:39:20 +00004688 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004689 { // acquire lock
4690 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004691 auto entry =
4692 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004693 needWake = enqueueInboundEventLocked(std::move(entry));
4694 } // release lock
4695
4696 if (needWake) {
4697 mLooper->wake();
4698 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004699}
4700
Prabir Pradhan5735a322022-04-11 17:23:34 +00004701InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004702 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004703 InputEventInjectionSync syncMode,
4704 std::chrono::milliseconds timeout,
4705 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004706 Result<void> eventValidation = validateInputEvent(*event);
4707 if (!eventValidation.ok()) {
4708 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4709 return InputEventInjectionResult::FAILED;
4710 }
4711
Prabir Pradhan65613802023-02-22 23:36:58 +00004712 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004713 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4714 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4715 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4716 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004717 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004718 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
Prabir Pradhan5735a322022-04-11 17:23:34 +00004720 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004722 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004723 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4724 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4725 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4726 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4727 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004728 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004729 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004730 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004731 }
4732
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004733 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4734 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4735
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004736 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004738 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004739 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004740 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004741 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004742 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4743 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4744 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004745 int32_t keyCode = incomingKey.getKeyCode();
4746 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004747 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004748 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004749 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4750 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4751 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4754 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004755 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756
4757 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4758 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004759 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4761 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4762 std::to_string(t.duration().count()).c_str());
4763 }
4764 }
4765
4766 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004767 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004768 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4769 incomingKey.getEventTime(), resolvedDeviceId,
4770 incomingKey.getSource(), incomingKey.getDisplayId(),
4771 policyFlags, action, flags, keyCode,
4772 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004773 incomingKey.getRepeatCount(),
4774 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004775 if (mTracer) {
4776 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4777 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004778 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 }
4781
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004782 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004783 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004784 const bool isPointerEvent =
4785 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4786 // If a pointer event has no displayId specified, inject it to the default display.
4787 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4788 ? ADISPLAY_ID_DEFAULT
4789 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004790 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791
4792 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004793 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004795 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4796 motionEvent.getAction(), eventTime,
4797 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4799 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4800 std::to_string(t.duration().count()).c_str());
4801 }
4802 }
4803
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004804 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4805 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4806 }
4807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004809 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004810 const size_t pointerCount = motionEvent.getPointerCount();
4811 const std::vector<PointerProperties>
4812 pointerProperties(motionEvent.getPointerProperties(),
4813 motionEvent.getPointerProperties() + pointerCount);
4814
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004815 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004816 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004817 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4818 *sampleEventTimes, resolvedDeviceId,
4819 motionEvent.getSource(), displayId, policyFlags,
4820 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004821 motionEvent.getActionButton(), flags,
4822 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004823 motionEvent.getButtonState(),
4824 motionEvent.getClassification(),
4825 motionEvent.getEdgeFlags(),
4826 motionEvent.getXPrecision(),
4827 motionEvent.getYPrecision(),
4828 motionEvent.getRawXCursorPosition(),
4829 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004830 motionEvent.getDownTime(), pointerProperties,
4831 std::vector<PointerCoords>(samplePointerCoords,
4832 samplePointerCoords +
4833 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004834 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004835 if (mTracer) {
4836 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4837 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004838 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004839 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004841 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004842 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004843 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4844 resolvedDeviceId, motionEvent.getSource(), displayId,
4845 policyFlags, motionEvent.getAction(),
4846 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004847 motionEvent.getMetaState(), motionEvent.getButtonState(),
4848 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4849 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4850 motionEvent.getRawXCursorPosition(),
4851 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4852 pointerProperties,
4853 std::vector<PointerCoords>(samplePointerCoords,
4854 samplePointerCoords +
4855 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004856 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4857 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004858 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004859 }
4860 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004863 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004864 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
4867
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004869 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004870 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004871 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004873 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004874 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876
4877 mLock.unlock();
4878
4879 if (needWake) {
4880 mLooper->wake();
4881 }
4882
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004885 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004887 if (syncMode == InputEventInjectionSync::NONE) {
4888 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 } else {
4890 for (;;) {
4891 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004892 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 break;
4894 }
4895
4896 nsecs_t remainingTimeout = endTime - now();
4897 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004898 if (DEBUG_INJECTION) {
4899 ALOGD("injectInputEvent - Timed out waiting for injection result "
4900 "to become available.");
4901 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 break;
4904 }
4905
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004906 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 }
4908
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004909 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4910 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004912 if (DEBUG_INJECTION) {
4913 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4914 injectionState->pendingForegroundDispatches);
4915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 nsecs_t remainingTimeout = endTime - now();
4917 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004918 if (DEBUG_INJECTION) {
4919 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4920 "dispatches to finish.");
4921 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004922 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 break;
4924 }
4925
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004926 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 }
4928 }
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 } // release lock
4931
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004932 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004933 LOG(INFO) << "injectInputEvent - Finished with result "
4934 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936
4937 return injectionResult;
4938}
4939
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004940std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004941 std::array<uint8_t, 32> calculatedHmac;
4942 std::unique_ptr<VerifiedInputEvent> result;
4943 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004944 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004945 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4946 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4947 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004948 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004949 break;
4950 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004951 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004952 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4953 VerifiedMotionEvent verifiedMotionEvent =
4954 verifiedMotionEventFromMotionEvent(motionEvent);
4955 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004956 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004957 break;
4958 }
4959 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004960 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004961 return nullptr;
4962 }
4963 }
4964 if (calculatedHmac == INVALID_HMAC) {
4965 return nullptr;
4966 }
tyiu1573a672023-02-21 22:38:32 +00004967 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004968 return nullptr;
4969 }
4970 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004971}
4972
Prabir Pradhan24047542023-11-02 17:14:59 +00004973void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004974 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004975 if (!entry.injectionState) {
4976 // Not an injected event.
4977 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004979
4980 InjectionState& injectionState = *entry.injectionState;
4981 if (DEBUG_INJECTION) {
4982 LOG(INFO) << "Setting input event injection result to "
4983 << ftl::enum_string(injectionResult);
4984 }
4985
4986 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4987 // Log the outcome since the injector did not wait for the injection result.
4988 switch (injectionResult) {
4989 case InputEventInjectionResult::SUCCEEDED:
4990 ALOGV("Asynchronous input event injection succeeded.");
4991 break;
4992 case InputEventInjectionResult::TARGET_MISMATCH:
4993 ALOGV("Asynchronous input event injection target mismatch.");
4994 break;
4995 case InputEventInjectionResult::FAILED:
4996 ALOGW("Asynchronous input event injection failed.");
4997 break;
4998 case InputEventInjectionResult::TIMED_OUT:
4999 ALOGW("Asynchronous input event injection timed out.");
5000 break;
5001 case InputEventInjectionResult::PENDING:
5002 ALOGE("Setting result to 'PENDING' for asynchronous injection");
5003 break;
5004 }
5005 }
5006
5007 injectionState.injectionResult = injectionResult;
5008 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005011void InputDispatcher::transformMotionEntryForInjectionLocked(
5012 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005013 // Input injection works in the logical display coordinate space, but the input pipeline works
5014 // display space, so we need to transform the injected events accordingly.
5015 const auto it = mDisplayInfos.find(entry.displayId);
5016 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005017 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005018
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005019 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5020 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5021 const vec2 cursor =
5022 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5023 {entry.xCursorPosition, entry.yCursorPosition});
5024 entry.xCursorPosition = cursor.x;
5025 entry.yCursorPosition = cursor.y;
5026 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005027 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005028 entry.pointerCoords[i] =
5029 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5030 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005031 }
5032}
5033
Prabir Pradhan24047542023-11-02 17:14:59 +00005034void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005035 if (entry.injectionState) {
5036 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
5038}
5039
Prabir Pradhan24047542023-11-02 17:14:59 +00005040void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005041 if (entry.injectionState) {
5042 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005044 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005045 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 }
5047 }
5048}
5049
chaviw98318de2021-05-19 16:45:23 -05005050const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005051 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005052 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005053 auto it = mWindowHandlesByDisplay.find(displayId);
5054 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005055}
5056
chaviw98318de2021-05-19 16:45:23 -05005057sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005058 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005059 if (windowHandleToken == nullptr) {
5060 return nullptr;
5061 }
5062
Prabir Pradhan16463382023-10-12 23:03:19 +00005063 if (!displayId) {
5064 // Look through all displays.
5065 for (auto& it : mWindowHandlesByDisplay) {
5066 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5067 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5068 if (windowHandle->getToken() == windowHandleToken) {
5069 return windowHandle;
5070 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005073 return nullptr;
5074 }
5075
Prabir Pradhan16463382023-10-12 23:03:19 +00005076 // Only look through the requested display.
5077 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005078 if (windowHandle->getToken() == windowHandleToken) {
5079 return windowHandle;
5080 }
5081 }
5082 return nullptr;
5083}
5084
chaviw98318de2021-05-19 16:45:23 -05005085sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5086 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005087 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005088 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5089 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005090 if (handle->getId() == windowHandle->getId() &&
5091 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005092 if (windowHandle->getInfo()->displayId != it.first) {
5093 ALOGE("Found window %s in display %" PRId32
5094 ", but it should belong to display %" PRId32,
5095 windowHandle->getName().c_str(), it.first,
5096 windowHandle->getInfo()->displayId);
5097 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005098 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005102 return nullptr;
5103}
5104
chaviw98318de2021-05-19 16:45:23 -05005105sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005106 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5107 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108}
5109
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005110ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5111 auto displayInfoIt = mDisplayInfos.find(displayId);
5112 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5113 : kIdentityTransform;
5114}
5115
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005116bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5117 const MotionEntry& motionEntry) const {
5118 const WindowInfo& info = *window->getInfo();
5119
5120 // Skip spy window targets that are not valid for targeted injection.
5121 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005122 return false;
5123 }
5124
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005125 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5126 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5127 return false;
5128 }
5129
5130 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5131 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5132 window->getName().c_str());
5133 return false;
5134 }
5135
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005136 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005137 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005138 ALOGW("Not sending touch to %s because there's no corresponding connection",
5139 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005140 return false;
5141 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005142
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005143 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005144 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005145 return false;
5146 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005147
5148 // Drop events that can't be trusted due to occlusion
5149 const auto [x, y] = resolveTouchedPosition(motionEntry);
5150 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5151 if (!isTouchTrustedLocked(occlusionInfo)) {
5152 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005153 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005154 for (const auto& log : occlusionInfo.debugInfo) {
5155 ALOGD("%s", log.c_str());
5156 }
5157 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005158 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5159 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005160 return false;
5161 }
5162
5163 // Drop touch events if requested by input feature
5164 if (shouldDropInput(motionEntry, window)) {
5165 return false;
5166 }
5167
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005168 // Ignore touches if stylus is down anywhere on screen
5169 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5170 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5171 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5172 return false;
5173 }
5174
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005175 return true;
5176}
5177
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005178void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005179 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5180 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005181 // Remove all handles on a display if there are no windows left.
5182 mWindowHandlesByDisplay.erase(displayId);
5183 return;
5184 }
5185
5186 // Since we compare the pointer of input window handles across window updates, we need
5187 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005188 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5189 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5190 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005191 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005192 }
5193
chaviw98318de2021-05-19 16:45:23 -05005194 std::vector<sp<WindowInfoHandle>> newHandles;
5195 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005196 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005197 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005198 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005199 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005200 const bool canReceiveInput =
5201 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5202 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005203 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005204 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005205 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005206 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005207 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005208 }
5209
5210 if (info->displayId != displayId) {
5211 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5212 handle->getName().c_str(), displayId, info->displayId);
5213 continue;
5214 }
5215
Robert Carredd13602020-04-13 17:24:34 -07005216 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5217 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005218 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005219 oldHandle->updateFrom(handle);
5220 newHandles.push_back(oldHandle);
5221 } else {
5222 newHandles.push_back(handle);
5223 }
5224 }
5225
5226 // Insert or replace
5227 mWindowHandlesByDisplay[displayId] = newHandles;
5228}
5229
Arthur Hungb92218b2018-08-14 12:00:21 +08005230/**
5231 * Called from InputManagerService, update window handle list by displayId that can receive input.
5232 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5233 * If set an empty list, remove all handles from the specific display.
5234 * For focused handle, check if need to change and send a cancel event to previous one.
5235 * For removed handle, check if need to send a cancel event if already in touch.
5236 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005237void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005238 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005239 if (DEBUG_FOCUS) {
5240 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005241 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005242 windowList += iwh->getName() + " ";
5243 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005244 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246
Prabir Pradhand65552b2021-10-07 11:23:50 -07005247 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005248 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005249 const WindowInfo& info = *window->getInfo();
5250
5251 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005252 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005253 if (noInputWindow && window->getToken() != nullptr) {
5254 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5255 window->getName().c_str());
5256 window->releaseChannel();
5257 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005258
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005259 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005260 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5261 !info.inputConfig.test(
5262 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005263 "%s has feature SPY, but is not a trusted overlay.",
5264 window->getName().c_str());
5265
Prabir Pradhand65552b2021-10-07 11:23:50 -07005266 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005267 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5268 !info.inputConfig.test(
5269 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005270 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5271 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005272 }
5273
Arthur Hung72d8dc32020-03-28 00:48:39 +00005274 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005275 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005276 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277
chaviw98318de2021-05-19 16:45:23 -05005278 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005279
chaviw98318de2021-05-19 16:45:23 -05005280 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005281
Vishnu Nairc519ff72021-01-21 08:23:08 -08005282 std::optional<FocusResolver::FocusChanges> changes =
5283 mFocusResolver.setInputWindows(displayId, windowHandles);
5284 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005285 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005288 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5289 mTouchStatesByDisplay.find(displayId);
5290 if (stateIt != mTouchStatesByDisplay.end()) {
5291 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005292 for (size_t i = 0; i < state.windows.size();) {
5293 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005294 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005295 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5296 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005297 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5298 "touched window was removed");
5299 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5300 // Since we are about to drop the touch, cancel the events for the wallpaper as
5301 // well.
5302 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5303 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5304 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5305 if (const auto& ww = state.getWallpaperWindow(); ww) {
5306 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005309 state.windows.erase(state.windows.begin() + i);
5310 } else {
5311 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 }
5313 }
arthurhungb89ccb02020-12-30 16:19:01 +08005314
arthurhung6d4bed92021-03-17 11:59:33 +08005315 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005316 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005317 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005318 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005319 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005320 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5321 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005322 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005323 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005324 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005325
Arthur Hung72d8dc32020-03-28 00:48:39 +00005326 // Release information for windows that are no longer present.
5327 // This ensures that unused input channels are released promptly.
5328 // Otherwise, they might stick around until the window handle is destroyed
5329 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005330 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005331 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005332 if (DEBUG_FOCUS) {
5333 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005334 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005335 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005336 }
chaviw291d88a2019-02-14 10:33:58 -08005337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338}
5339
5340void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005341 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005342 if (DEBUG_FOCUS) {
5343 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5344 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5345 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005346 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005347 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005348 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 } // release lock
5350
5351 // Wake up poll loop since it may need to make new input dispatching choices.
5352 mLooper->wake();
5353}
5354
Vishnu Nair599f1412021-06-21 10:39:58 -07005355void InputDispatcher::setFocusedApplicationLocked(
5356 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5357 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5358 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5359
5360 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5361 return; // This application is already focused. No need to wake up or change anything.
5362 }
5363
5364 // Set the new application handle.
5365 if (inputApplicationHandle != nullptr) {
5366 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5367 } else {
5368 mFocusedApplicationHandlesByDisplay.erase(displayId);
5369 }
5370
5371 // No matter what the old focused application was, stop waiting on it because it is
5372 // no longer focused.
5373 resetNoFocusedWindowTimeoutLocked();
5374}
5375
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005376void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5377 if (interval.count() < 0) {
5378 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5379 }
5380 std::scoped_lock _l(mLock);
5381 mMinTimeBetweenUserActivityPokes = interval;
5382}
5383
Tiger Huang721e26f2018-07-24 22:26:19 +08005384/**
5385 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5386 * the display not specified.
5387 *
5388 * We track any unreleased events for each window. If a window loses the ability to receive the
5389 * released event, we will send a cancel event to it. So when the focused display is changed, we
5390 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5391 * display. The display-specified events won't be affected.
5392 */
5393void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005394 if (DEBUG_FOCUS) {
5395 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5396 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005397 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005398 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005399
5400 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005401 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005402 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005403 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005404 const auto windowHandle =
5405 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5406 if (windowHandle == nullptr) {
5407 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005408 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005409 CancelationOptions
5410 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5411 "The display which contains this window no longer has focus.");
5412 options.displayId = ADISPLAY_ID_NONE;
5413 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005414 }
5415 mFocusedDisplayId = displayId;
5416
Chris Ye3c2d6f52020-08-09 10:39:48 -07005417 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005418 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005419 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005420
Vishnu Nairad321cd2020-08-20 16:40:21 -07005421 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005422 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005423 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005424 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005425 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005426 }
5427 }
5428 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005429 } // release lock
5430
5431 // Wake up poll loop since it may need to make new input dispatching choices.
5432 mLooper->wake();
5433}
5434
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005436 if (DEBUG_FOCUS) {
5437 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439
5440 bool changed;
5441 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005442 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443
5444 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5445 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005446 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 }
5448
5449 if (mDispatchEnabled && !enabled) {
5450 resetAndDropEverythingLocked("dispatcher is being disabled");
5451 }
5452
5453 mDispatchEnabled = enabled;
5454 mDispatchFrozen = frozen;
5455 changed = true;
5456 } else {
5457 changed = false;
5458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 } // release lock
5460
5461 if (changed) {
5462 // Wake up poll loop since it may need to make new input dispatching choices.
5463 mLooper->wake();
5464 }
5465}
5466
5467void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005468 if (DEBUG_FOCUS) {
5469 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471
5472 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005473 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474
5475 if (mInputFilterEnabled == enabled) {
5476 return;
5477 }
5478
5479 mInputFilterEnabled = enabled;
5480 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5481 } // release lock
5482
5483 // Wake up poll loop since there might be work to do to drop everything.
5484 mLooper->wake();
5485}
5486
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005487bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005488 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005489 bool needWake = false;
5490 {
5491 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005492 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005493 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005494 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005495 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5496 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005497 mTouchModePerDisplay.count(displayId) == 0
5498 ? "not set"
5499 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5500
Antonio Kantek15beb512022-06-13 22:35:41 +00005501 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5502 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005503 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005504 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005505 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005506 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5507 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005508 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005509 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005510 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005511 return false;
5512 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005513 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005514 mTouchModePerDisplay[displayId] = inTouchMode;
5515 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5516 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005517 needWake = enqueueInboundEventLocked(std::move(entry));
5518 } // release lock
5519
5520 if (needWake) {
5521 mLooper->wake();
5522 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005523 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005524}
5525
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005526bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005527 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5528 if (focusedToken == nullptr) {
5529 return false;
5530 }
5531 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5532 return isWindowOwnedBy(windowHandle, pid, uid);
5533}
5534
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005535bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005536 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5537 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5538 const sp<WindowInfoHandle> windowHandle =
5539 getWindowHandleLocked(connectionToken);
5540 return isWindowOwnedBy(windowHandle, pid, uid);
5541 }) != mInteractionConnectionTokens.end();
5542}
5543
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005544void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5545 if (opacity < 0 || opacity > 1) {
5546 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5547 return;
5548 }
5549
5550 std::scoped_lock lock(mLock);
5551 mMaximumObscuringOpacityForTouch = opacity;
5552}
5553
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005554std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5555InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005556 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5557 for (TouchedWindow& w : state.windows) {
5558 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005559 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005560 }
5561 }
5562 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005563 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005564}
5565
Prabir Pradhan367f3432024-02-13 23:05:58 +00005566bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5567 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005568 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005569 if (DEBUG_FOCUS) {
5570 ALOGD("Trivial transfer to same window.");
5571 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005572 return true;
5573 }
5574
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005576 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577
Arthur Hungabbb9d82021-09-01 14:52:30 +00005578 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005579 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005580
Arthur Hungabbb9d82021-09-01 14:52:30 +00005581 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005582 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 return false;
5584 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005585 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5586 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005587 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5588 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005589 return false;
5590 }
5591 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005592
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005593 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5594 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5595 if (!toWindowHandle) {
5596 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005597 return false;
5598 }
5599
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005600 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005601 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005602 touchedWindow->windowHandle->getName().c_str(),
5603 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 }
5605
Arthur Hungabbb9d82021-09-01 14:52:30 +00005606 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005607 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005608 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005609 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005612 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005613 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005614 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005615 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005616 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005617 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005618 // Transferring touch focus using this API should not effect the focused window.
5619 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005620 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005621 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622
Arthur Hungabbb9d82021-09-01 14:52:30 +00005623 // Store the dragging window.
5624 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005625 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005626 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5627 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005628 return false;
5629 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005630 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005631 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005632 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634
Arthur Hungabbb9d82021-09-01 14:52:30 +00005635 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005636 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5637 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005638 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005639 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005640 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5641 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005642 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005643 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5644 newTargetFlags);
5645
5646 // Check if the wallpaper window should deliver the corresponding event.
5647 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005648 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 } // release lock
5651
5652 // Wake up poll loop since it may need to make new input dispatching choices.
5653 mLooper->wake();
5654 return true;
5655}
5656
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005657/**
5658 * Get the touched foreground window on the given display.
5659 * Return null if there are no windows touched on that display, or if more than one foreground
5660 * window is being touched.
5661 */
5662sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5663 auto stateIt = mTouchStatesByDisplay.find(displayId);
5664 if (stateIt == mTouchStatesByDisplay.end()) {
5665 ALOGI("No touch state on display %" PRId32, displayId);
5666 return nullptr;
5667 }
5668
5669 const TouchState& state = stateIt->second;
5670 sp<WindowInfoHandle> touchedForegroundWindow;
5671 // If multiple foreground windows are touched, return nullptr
5672 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005673 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005674 if (touchedForegroundWindow != nullptr) {
5675 ALOGI("Two or more foreground windows: %s and %s",
5676 touchedForegroundWindow->getName().c_str(),
5677 window.windowHandle->getName().c_str());
5678 return nullptr;
5679 }
5680 touchedForegroundWindow = window.windowHandle;
5681 }
5682 }
5683 return touchedForegroundWindow;
5684}
5685
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005686// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005687bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5688 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005689 sp<IBinder> fromToken;
5690 { // acquire lock
5691 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005692 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005693 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005694 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5695 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005696 return false;
5697 }
5698
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005699 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5700 if (from == nullptr) {
5701 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5702 return false;
5703 }
5704
5705 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005706 } // release lock
5707
Prabir Pradhan367f3432024-02-13 23:05:58 +00005708 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005709}
5710
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005712 if (DEBUG_FOCUS) {
5713 ALOGD("Resetting and dropping all events (%s).", reason);
5714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715
Michael Wrightfb04fd52022-11-24 22:31:11 +00005716 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 synthesizeCancelationEventsForAllConnectionsLocked(options);
5718
5719 resetKeyRepeatLocked();
5720 releasePendingEventLocked();
5721 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005724 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005725 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726}
5727
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005728void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005729 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 dumpDispatchStateLocked(dump);
5731
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005732 std::istringstream stream(dump);
5733 std::string line;
5734
5735 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005736 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738}
5739
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005740std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005741 std::string dump;
5742
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005743 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5744 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005745
5746 std::string windowName = "None";
5747 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005748 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005749 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5750 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5751 : "token has capture without window";
5752 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005753 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005754
5755 return dump;
5756}
5757
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005758void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005759 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5760 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5761 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005762 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763
Tiger Huang721e26f2018-07-24 22:26:19 +08005764 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5765 dump += StringPrintf(INDENT "FocusedApplications:\n");
5766 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5767 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005768 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005769 const std::chrono::duration timeout =
5770 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005771 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005772 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005773 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005776 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005778
Vishnu Nairc519ff72021-01-21 08:23:08 -08005779 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005780 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005782 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005783 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005784 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005785 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5786 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 }
5788 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791
arthurhung6d4bed92021-03-17 11:59:33 +08005792 if (mDragState) {
5793 dump += StringPrintf(INDENT "DragState:\n");
5794 mDragState->dump(dump, INDENT2);
5795 }
5796
Arthur Hungb92218b2018-08-14 12:00:21 +08005797 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005798 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5799 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5800 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5801 const auto& displayInfo = it->second;
5802 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5803 displayInfo.logicalHeight);
5804 displayInfo.transform.dump(dump, "transform", INDENT4);
5805 } else {
5806 dump += INDENT2 "No DisplayInfo found!\n";
5807 }
5808
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005809 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005810 dump += INDENT2 "Windows:\n";
5811 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005812 dump += StringPrintf(INDENT3 "%zu: %s", i,
5813 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005814 }
5815 } else {
5816 dump += INDENT2 "Windows: <none>\n";
5817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 }
5819 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005820 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 }
5822
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005823 if (!mGlobalMonitorsByDisplay.empty()) {
5824 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5825 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005826 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005829 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830 }
5831
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833
5834 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005835 if (!mRecentQueue.empty()) {
5836 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005837 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005838 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005839 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005840 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 }
5842 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005843 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
5845
5846 // Dump event currently being dispatched.
5847 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005848 dump += INDENT "PendingEvent:\n";
5849 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005850 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005851 dump += StringPrintf(", age=%" PRId64 "ms\n",
5852 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005854 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 }
5856
5857 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005858 if (!mInboundQueue.empty()) {
5859 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005860 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005861 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005862 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005863 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 }
5865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005866 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 }
5868
Prabir Pradhancef936d2021-07-21 16:17:52 +00005869 if (!mCommandQueue.empty()) {
5870 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5871 } else {
5872 dump += INDENT "CommandQueue: <empty>\n";
5873 }
5874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005875 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005876 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005877 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005878 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005879 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005880 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005881 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005882 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005883 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005885 if (!connection->outboundQueue.empty()) {
5886 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5887 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005888 dump += dumpQueue(connection->outboundQueue, currentTime);
5889
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005891 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 }
5893
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005894 if (!connection->waitQueue.empty()) {
5895 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5896 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005897 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005899 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005901 std::string inputStateDump = streamableToString(connection->inputState);
5902 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005903 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005904 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 }
5907 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005908 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909 }
5910
Antonio Kantek15beb512022-06-13 22:35:41 +00005911 if (!mTouchModePerDisplay.empty()) {
5912 dump += INDENT "TouchModePerDisplay:\n";
5913 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5914 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5915 std::to_string(touchMode).c_str());
5916 }
5917 } else {
5918 dump += INDENT "TouchModePerDisplay: <none>\n";
5919 }
5920
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005921 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005922 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5923 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5924 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005925 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005926 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005927 dump += INDENT "InputTracer: ";
5928 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929}
5930
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005931void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005932 const size_t numMonitors = monitors.size();
5933 for (size_t i = 0; i < numMonitors; i++) {
5934 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005935 const std::shared_ptr<Connection>& connection = monitor.connection;
5936 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005937 dump += "\n";
5938 }
5939}
5940
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005941class LooperEventCallback : public LooperCallback {
5942public:
5943 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5944 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5945
5946private:
5947 std::function<int(int events)> mCallback;
5948};
5949
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005950Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005951 if (DEBUG_CHANNEL_CREATION) {
5952 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005955 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005956 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005957 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005958
5959 if (result) {
5960 return base::Error(result) << "Failed to open input channel pair with name " << name;
5961 }
5962
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005964 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005965 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005966 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005967 std::shared_ptr<Connection> connection =
5968 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5969 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005971 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5972 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005973 ALOGE("Created a new connection, but the token %p is already known", token.get());
5974 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005975
5976 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5977 this, std::placeholders::_1, token);
5978
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005979 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005980 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 } // release lock
5982
5983 // Wake the looper because some connections have changed.
5984 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005985 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986}
5987
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005988Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005989 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005990 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005991 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005992 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005993 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005994 if (result) {
5995 return base::Error(result) << "Failed to open input channel pair with name " << name;
5996 }
5997
Michael Wright3dd60e22019-03-27 22:06:44 +00005998 { // acquire lock
5999 std::scoped_lock _l(mLock);
6000
6001 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07006002 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
6003 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006004 }
6005
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006006 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006007 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006008 std::shared_ptr<Connection> connection =
6009 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6010 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006011
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006012 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6013 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006014 ALOGE("Created a new connection, but the token %p is already known", token.get());
6015 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006016
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006017 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6018 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006019
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006020 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006021
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006022 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006023 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006024 }
Garfield Tan15601662020-09-22 15:32:38 -07006025
Michael Wright3dd60e22019-03-27 22:06:44 +00006026 // Wake the looper because some connections have changed.
6027 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006028 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006029}
6030
Garfield Tan15601662020-09-22 15:32:38 -07006031status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006033 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034
Harry Cutts33476232023-01-30 19:57:29 +00006035 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036 if (status) {
6037 return status;
6038 }
6039 } // release lock
6040
6041 // Wake the poll loop because removing the connection may have changed the current
6042 // synchronization state.
6043 mLooper->wake();
6044 return OK;
6045}
6046
Garfield Tan15601662020-09-22 15:32:38 -07006047status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6048 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006049 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006050 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006051 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 return BAD_VALUE;
6053 }
6054
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006055 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006056
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006058 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059 }
6060
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006061 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062
6063 nsecs_t currentTime = now();
6064 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6065
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006066 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006067 return OK;
6068}
6069
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006070void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6072 auto& [displayId, monitors] = *it;
6073 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006074 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006075 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006076
Michael Wright3dd60e22019-03-27 22:06:44 +00006077 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006078 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006079 } else {
6080 ++it;
6081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 }
6083}
6084
Michael Wright3dd60e22019-03-27 22:06:44 +00006085status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006086 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006087 return pilferPointersLocked(token);
6088}
Michael Wright3dd60e22019-03-27 22:06:44 +00006089
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006090status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006091 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6092 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006093 LOG(WARNING)
6094 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006095 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006096 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006097
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006098 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006099 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006100 LOG(WARNING)
6101 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6102 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006103 return BAD_VALUE;
6104 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006105 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006106 if (deviceIds.empty()) {
6107 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006108 return BAD_VALUE;
6109 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006110
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006111 for (const DeviceId deviceId : deviceIds) {
6112 TouchState& state = *statePtr;
6113 TouchedWindow& window = *windowPtr;
6114 // Send cancel events to all the input channels we're stealing from.
6115 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6116 "input channel stole pointer stream");
6117 options.deviceId = deviceId;
6118 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006119 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6120 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006121 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006122
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006123 std::string canceledWindows;
6124 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006125 if (w.windowHandle->getToken() != token) {
6126 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006127 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006128 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006129 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006130 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006131 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006132 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006133 << " is stealing input gesture for device " << deviceId << " from "
6134 << canceledWindows;
6135
6136 // Prevent the gesture from being sent to any other windows.
6137 // This only blocks relevant pointers to be sent to other windows
6138 window.addPilferingPointers(deviceId, pointerIds);
6139
6140 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006141 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006142 return OK;
6143}
6144
Prabir Pradhan99987712020-11-10 18:43:05 -08006145void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6146 { // acquire lock
6147 std::scoped_lock _l(mLock);
6148 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006149 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006150 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6151 windowHandle != nullptr ? windowHandle->getName().c_str()
6152 : "token without window");
6153 }
6154
Vishnu Nairc519ff72021-01-21 08:23:08 -08006155 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006156 if (focusedToken != windowToken) {
6157 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6158 enabled ? "enable" : "disable");
6159 return;
6160 }
6161
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006162 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006163 ALOGW("Ignoring request to %s Pointer Capture: "
6164 "window has %s requested pointer capture.",
6165 enabled ? "enable" : "disable", enabled ? "already" : "not");
6166 return;
6167 }
6168
Christine Franksb768bb42021-11-29 12:11:31 -08006169 if (enabled) {
6170 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6171 mIneligibleDisplaysForPointerCapture.end(),
6172 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6173 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6174 return;
6175 }
6176 }
6177
Prabir Pradhan99987712020-11-10 18:43:05 -08006178 setPointerCaptureLocked(enabled);
6179 } // release lock
6180
6181 // Wake the thread to process command entries.
6182 mLooper->wake();
6183}
6184
Christine Franksb768bb42021-11-29 12:11:31 -08006185void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6186 { // acquire lock
6187 std::scoped_lock _l(mLock);
6188 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6189 if (!isEligible) {
6190 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6191 }
6192 } // release lock
6193}
6194
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006195std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006196 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006197 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006198 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006199 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006200 }
6201 }
6202 }
6203 return std::nullopt;
6204}
6205
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006206std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6207 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006208 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006209 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006210 }
6211
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006212 for (const auto& [token, connection] : mConnectionsByToken) {
6213 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006214 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215 }
6216 }
Robert Carr4e670e52018-08-15 13:26:12 -07006217
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006218 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219}
6220
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006221std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006222 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006223 if (connection == nullptr) {
6224 return "<nullptr>";
6225 }
6226 return connection->getInputChannelName();
6227}
6228
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006229void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006230 mAnrTracker.eraseToken(connection->getToken());
6231 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006232}
6233
Prabir Pradhancef936d2021-07-21 16:17:52 +00006234void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006235 const std::shared_ptr<Connection>& connection,
6236 uint32_t seq, bool handled,
6237 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006238 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006239 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006240
6241 { // Start critical section
6242 auto dispatchEntryIt =
6243 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6244 [seq](auto& e) { return e->seq == seq; });
6245 if (dispatchEntryIt == connection->waitQueue.end()) {
6246 return;
6247 }
6248
6249 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6250
6251 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6252 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006253 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006254 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6255 }
6256 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006257 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006258 dispatchEntry.deliveryTime, consumeTime, finishTime);
6259 }
6260
6261 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006262 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6263 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006264 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006265 }
6266 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267
6268 // Dequeue the event and start the next cycle.
6269 // Because the lock might have been released, it is possible that the
6270 // contents of the wait queue to have been drained, so we need to double-check
6271 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006272 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6273 [seq](auto& e) { return e->seq == seq; });
6274 if (entryIt != connection->waitQueue.end()) {
6275 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6276 connection->waitQueue.erase(entryIt);
6277
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006278 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006279 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6280 if (!connection->responsive) {
6281 connection->responsive = isConnectionResponsive(*connection);
6282 if (connection->responsive) {
6283 // The connection was unresponsive, and now it's responsive.
6284 processConnectionResponsiveLocked(*connection);
6285 }
6286 }
6287 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006288 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006289 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6290 // Only dispatch fallbacks if there is a window for the connection.
6291 if (windowHandle != nullptr) {
6292 const auto inputTarget =
6293 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6294 dispatchEntry->targetFlags,
6295 fallbackKeyEntry->downTime);
6296 if (inputTarget.has_value()) {
6297 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6298 *inputTarget);
6299 }
6300 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006302 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006303 }
6304
6305 // Start the next dispatch cycle for this connection.
6306 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307}
6308
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6310 const sp<IBinder>& newToken) {
6311 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6312 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006313 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006314 };
6315 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316}
6317
Prabir Pradhancef936d2021-07-21 16:17:52 +00006318void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6319 auto command = [this, token, x, y]() REQUIRES(mLock) {
6320 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006321 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006322 };
6323 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006324}
6325
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006326void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006327 if (connection == nullptr) {
6328 LOG_ALWAYS_FATAL("Caller must check for nullness");
6329 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006330 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6331 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006332 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006333 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006334 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006335 return;
6336 }
6337 /**
6338 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6339 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6340 * has changed. This could cause newer entries to time out before the already dispatched
6341 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6342 * processes the events linearly. So providing information about the oldest entry seems to be
6343 * most useful.
6344 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006345 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6346 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006347 std::string reason =
6348 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006349 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006350 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006351 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006352 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006353 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006354
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006355 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6356
6357 // Stop waking up for events on this connection, it is already unresponsive
6358 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006359}
6360
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006361void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6362 std::string reason =
6363 StringPrintf("%s does not have a focused window", application->getName().c_str());
6364 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006365
Yabin Cui8eb9c552023-06-08 18:05:07 +00006366 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006368 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 };
6370 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006371}
6372
chaviw98318de2021-05-19 16:45:23 -05006373void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006374 const std::string& reason) {
6375 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6376 updateLastAnrStateLocked(windowLabel, reason);
6377}
6378
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006379void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6380 const std::string& reason) {
6381 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006382 updateLastAnrStateLocked(windowLabel, reason);
6383}
6384
6385void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6386 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006388 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 struct tm tm;
6390 localtime_r(&t, &tm);
6391 char timestr[64];
6392 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006393 mLastAnrState.clear();
6394 mLastAnrState += INDENT "ANR:\n";
6395 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006396 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6397 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006398 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399}
6400
Prabir Pradhancef936d2021-07-21 16:17:52 +00006401void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006402 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006403 const KeyEvent event = createKeyEvent(entry);
6404 nsecs_t delay = 0;
6405 { // release lock
6406 scoped_unlock unlock(mLock);
6407 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006408 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006409 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6410 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6411 std::to_string(t.duration().count()).c_str());
6412 }
6413 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414
6415 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006416 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006417 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006418 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006420 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006421 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423}
6424
Prabir Pradhancef936d2021-07-21 16:17:52 +00006425void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006426 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006427 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006428 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006429 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006430 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006431 };
6432 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006433}
6434
Prabir Pradhanedd96402022-02-15 01:46:16 -08006435void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006436 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006437 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006438 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006439 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006440 };
6441 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006442}
6443
6444/**
6445 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6446 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6447 * command entry to the command queue.
6448 */
6449void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6450 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006451 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006452 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006453 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006454 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006455 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006456 pid = findMonitorPidByTokenLocked(connectionToken);
6457 } else {
6458 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006459 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006460 reason.c_str());
6461 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6462 if (handle != nullptr) {
6463 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006464 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006465 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006466 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006467}
6468
6469/**
6470 * Tell the policy that a connection has become responsive so that it can stop ANR.
6471 */
6472void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006473 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006474 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006475 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006476 pid = findMonitorPidByTokenLocked(connectionToken);
6477 } else {
6478 // The connection is a window
6479 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6480 if (handle != nullptr) {
6481 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006482 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006483 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006484 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006485}
6486
Prabir Pradhan24047542023-11-02 17:14:59 +00006487std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006488 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006489 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006490 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006491 if (!handled) {
6492 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006493 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006494 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006495 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 // Get the fallback key state.
6499 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006500 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006501 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006502 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 connection->inputState.removeFallbackKey(originalKeyCode);
6504 }
6505
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006506 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 // If the application handles the original key for which we previously
6508 // generated a fallback or if the window is not a foreground window,
6509 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006510 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006512 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6513 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6514 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6515 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6516 keyEntry.policyFlags);
6517 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006518 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006519 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006520
6521 mLock.unlock();
6522
Prabir Pradhana41d2442023-04-20 21:30:40 +00006523 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006524 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6525 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006526 unhandledKeyFallback) {
6527 event = *unhandledKeyFallback;
6528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529
6530 mLock.lock();
6531
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006532 // Cancel the fallback key, but only if we still have a window for the channel.
6533 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006534 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006535 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6536 if (windowHandle != nullptr) {
6537 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6538 "application handled the original non-fallback key "
6539 "or is no longer a foreground target, "
6540 "canceling previously dispatched fallback key");
6541 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006542 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006545 connection->inputState.removeFallbackKey(originalKeyCode);
6546 }
6547 } else {
6548 // If the application did not handle a non-fallback key, first check
6549 // that we are in a good state to perform unhandled key event processing
6550 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006551 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006552 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006553 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6554 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6555 "since this is not an initial down. "
6556 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6557 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6558 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006559 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006563 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6564 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6565 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6566 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6567 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006568 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006569
6570 mLock.unlock();
6571
Prabir Pradhana41d2442023-04-20 21:30:40 +00006572 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006573 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6574 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006575 fb) {
6576 fallback = true;
6577 event = *fb;
6578 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579
6580 mLock.lock();
6581
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006582 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006584 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006585 }
6586
6587 // Latch the fallback keycode for this key on an initial down.
6588 // The fallback keycode cannot change at any other point in the lifecycle.
6589 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006591 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006592 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006593 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006594 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006595 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006596 }
6597
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006598 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006599
6600 // Cancel the fallback key if the policy decides not to send it anymore.
6601 // We will continue to dispatch the key to the policy but we will no
6602 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006603 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6604 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006605 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6606 if (fallback) {
6607 ALOGD("Unhandled key event: Policy requested to send key %d"
6608 "as a fallback for %d, but on the DOWN it had requested "
6609 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006610 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006611 } else {
6612 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6613 "but on the DOWN it had requested to send %d. "
6614 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006615 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006616 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006617 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006619 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6620 if (windowHandle != nullptr) {
6621 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6622 "canceling fallback, policy no longer desires it");
6623 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006624 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006625 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006626
6627 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006628 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006629 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006630 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006631 }
6632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006633
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006634 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6635 {
6636 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006637 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006638 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006639 for (const auto& [key, value] : fallbackKeys) {
6640 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006641 }
6642 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6643 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006644 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006645 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006646
6647 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006648 // Return the fallback key that we want dispatched to the channel.
6649 std::unique_ptr<KeyEntry> newEntry =
6650 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6651 event.getEventTime(), event.getDeviceId(),
6652 event.getSource(), event.getDisplayId(),
6653 keyEntry.policyFlags, keyEntry.action,
6654 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6655 *fallbackKeyCode, event.getScanCode(),
6656 event.getMetaState(), event.getRepeatCount(),
6657 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006658 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6659 ALOGD("Unhandled key event: Dispatching fallback key. "
6660 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006661 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006662 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006663 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006664 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006665 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6666 ALOGD("Unhandled key event: No fallback key.");
6667 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006668
6669 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006670 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006671 }
6672 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006673 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674}
6675
Michael Wrightd02c5b62014-02-10 15:10:22 -08006676void InputDispatcher::traceInboundQueueLengthLocked() {
6677 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006678 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006679 }
6680}
6681
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006682void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006683 if (ATRACE_ENABLED()) {
6684 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006685 snprintf(counterName, sizeof(counterName), "oq:%s",
6686 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006687 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688 }
6689}
6690
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006691void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006692 if (ATRACE_ENABLED()) {
6693 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006694 snprintf(counterName, sizeof(counterName), "wq:%s",
6695 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006696 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006697 }
6698}
6699
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006700void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006701 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006703 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704 dumpDispatchStateLocked(dump);
6705
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006706 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006707 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006708 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006709 }
6710}
6711
6712void InputDispatcher::monitor() {
6713 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006714 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006715 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006716 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006717}
6718
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006719/**
6720 * Wake up the dispatcher and wait until it processes all events and commands.
6721 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6722 * this method can be safely called from any thread, as long as you've ensured that
6723 * the work you are interested in completing has already been queued.
6724 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006725bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006726 /**
6727 * Timeout should represent the longest possible time that a device might spend processing
6728 * events and commands.
6729 */
6730 constexpr std::chrono::duration TIMEOUT = 100ms;
6731 std::unique_lock lock(mLock);
6732 mLooper->wake();
6733 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6734 return result == std::cv_status::no_timeout;
6735}
6736
Vishnu Naire798b472020-07-23 13:52:21 -07006737/**
6738 * Sets focus to the window identified by the token. This must be called
6739 * after updating any input window handles.
6740 *
6741 * Params:
6742 * request.token - input channel token used to identify the window that should gain focus.
6743 * request.focusedToken - the token that the caller expects currently to be focused. If the
6744 * specified token does not match the currently focused window, this request will be dropped.
6745 * If the specified focused token matches the currently focused window, the call will succeed.
6746 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6747 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6748 * when requesting the focus change. This determines which request gets
6749 * precedence if there is a focus change request from another source such as pointer down.
6750 */
Vishnu Nair958da932020-08-21 17:12:37 -07006751void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6752 { // acquire lock
6753 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006754 std::optional<FocusResolver::FocusChanges> changes =
6755 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6756 if (changes) {
6757 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006758 }
6759 } // release lock
6760 // Wake up poll loop since it may need to make new input dispatching choices.
6761 mLooper->wake();
6762}
6763
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006764void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6765 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006766 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006767 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6768 ? removedFocusedWindowHandle
6769 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6770 if (resolvedWindow == nullptr) {
6771 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006772 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006773 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6774 "focus left window");
6775 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6776 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006777 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006778 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006779 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006780 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006781 }
6782
Prabir Pradhan99987712020-11-10 18:43:05 -08006783 // If a window has pointer capture, then it must have focus. We need to ensure that this
6784 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6785 // If the window loses focus before it loses pointer capture, then the window can be in a state
6786 // where it has pointer capture but not focus, violating the contract. Therefore we must
6787 // dispatch the pointer capture event before the focus event. Since focus events are added to
6788 // the front of the queue (above), we add the pointer capture event to the front of the queue
6789 // after the focus events are added. This ensures the pointer capture event ends up at the
6790 // front.
6791 disablePointerCaptureForcedLocked();
6792
Vishnu Nairc519ff72021-01-21 08:23:08 -08006793 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006794 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006795 }
6796}
Vishnu Nair958da932020-08-21 17:12:37 -07006797
Prabir Pradhan99987712020-11-10 18:43:05 -08006798void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006799 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006800 return;
6801 }
6802
6803 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6804
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006805 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006806 setPointerCaptureLocked(false);
6807 }
6808
6809 if (!mWindowTokenWithPointerCapture) {
6810 // No need to send capture changes because no window has capture.
6811 return;
6812 }
6813
6814 if (mPendingEvent != nullptr) {
6815 // Move the pending event to the front of the queue. This will give the chance
6816 // for the pending event to be dropped if it is a captured event.
6817 mInboundQueue.push_front(mPendingEvent);
6818 mPendingEvent = nullptr;
6819 }
6820
6821 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006822 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006823 mInboundQueue.push_front(std::move(entry));
6824}
6825
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006826void InputDispatcher::setPointerCaptureLocked(bool enable) {
6827 mCurrentPointerCaptureRequest.enable = enable;
6828 mCurrentPointerCaptureRequest.seq++;
6829 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006830 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006831 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006832 };
6833 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006834}
6835
Vishnu Nair599f1412021-06-21 10:39:58 -07006836void InputDispatcher::displayRemoved(int32_t displayId) {
6837 { // acquire lock
6838 std::scoped_lock _l(mLock);
6839 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006840 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006841 setFocusedApplicationLocked(displayId, nullptr);
6842 // Call focus resolver to clean up stale requests. This must be called after input windows
6843 // have been removed for the removed display.
6844 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006845 // Reset pointer capture eligibility, regardless of previous state.
6846 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006847 // Remove the associated touch mode state.
6848 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006849 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006850 } // release lock
6851
6852 // Wake up poll loop since it may need to make new input dispatching choices.
6853 mLooper->wake();
6854}
6855
Patrick Williamsd828f302023-04-28 17:52:08 -05006856void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006857 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6858 {
6859 // acquire lock
6860 std::scoped_lock _l(mLock);
6861 logDispatchStateLocked();
6862 }
6863 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6864 result.error().message().c_str());
6865 };
chaviw15fab6f2021-06-07 14:15:52 -05006866 // The listener sends the windows as a flattened array. Separate the windows by display for
6867 // more convenient parsing.
6868 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006869 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006870 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006871 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006872 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006873
6874 { // acquire lock
6875 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006876
6877 // Ensure that we have an entry created for all existing displays so that if a displayId has
6878 // no windows, we can tell that the windows were removed from the display.
6879 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6880 handlesPerDisplay[displayId];
6881 }
6882
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006883 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006884 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006885 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6886 }
6887
6888 for (const auto& [displayId, handles] : handlesPerDisplay) {
6889 setInputWindowsLocked(handles, displayId);
6890 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006891
6892 if (update.vsyncId < mWindowInfosVsyncId) {
6893 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6894 ", current update vsync id: %" PRId64,
6895 mWindowInfosVsyncId, update.vsyncId);
6896 }
6897 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006898 }
6899 // Wake up poll loop since it may need to make new input dispatching choices.
6900 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006901}
6902
Vishnu Nair062a8672021-09-03 16:07:44 -07006903bool InputDispatcher::shouldDropInput(
6904 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006905 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6906 (windowHandle->getInfo()->inputConfig.test(
6907 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006908 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006909 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6910 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006911 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006912 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006913 windowHandle->getInfo()->displayId);
6914 return true;
6915 }
6916 return false;
6917}
6918
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006919void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006920 const gui::WindowInfosUpdate& update) {
6921 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006922}
6923
Arthur Hungdfd528e2021-12-08 13:23:04 +00006924void InputDispatcher::cancelCurrentTouch() {
6925 {
6926 std::scoped_lock _l(mLock);
6927 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006928 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006929 "cancel current touch");
6930 synthesizeCancelationEventsForAllConnectionsLocked(options);
6931
6932 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006933 }
6934 // Wake up poll loop since there might be work to do.
6935 mLooper->wake();
6936}
6937
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006938void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6939 std::scoped_lock _l(mLock);
6940 mMonitorDispatchingTimeout = timeout;
6941}
6942
Arthur Hungc539dbb2022-12-08 07:45:36 +00006943void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6944 const sp<WindowInfoHandle>& oldWindowHandle,
6945 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006946 TouchState& state, int32_t deviceId,
6947 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006948 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006949 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006950 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6951 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6952 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6953 newWindowHandle->getInfo()->inputConfig.test(
6954 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6955 const sp<WindowInfoHandle> oldWallpaper =
6956 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6957 const sp<WindowInfoHandle> newWallpaper =
6958 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6959 if (oldWallpaper == newWallpaper) {
6960 return;
6961 }
6962
6963 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006964 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006965 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006966 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006967 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006968 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 }
6970
6971 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006972 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6973 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006974 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006975 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006976 }
6977}
6978
6979void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6980 ftl::Flags<InputTarget::Flags> newTargetFlags,
6981 const sp<WindowInfoHandle> fromWindowHandle,
6982 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006983 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006984 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006985 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6986 fromWindowHandle->getInfo()->inputConfig.test(
6987 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6988 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6989 toWindowHandle->getInfo()->inputConfig.test(
6990 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6991
6992 const sp<WindowInfoHandle> oldWallpaper =
6993 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6994 const sp<WindowInfoHandle> newWallpaper =
6995 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6996 if (oldWallpaper == newWallpaper) {
6997 return;
6998 }
6999
7000 if (oldWallpaper != nullptr) {
7001 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
7002 "transferring touch focus to another window");
7003 state.removeWindowByToken(oldWallpaper->getToken());
7004 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7005 }
7006
7007 if (newWallpaper != nullptr) {
7008 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007009 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7010 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007011 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7012 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007013 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007014 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007015 std::shared_ptr<Connection> wallpaperConnection =
7016 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007017 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007018 std::shared_ptr<Connection> toConnection =
7019 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007020 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7021 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7022 wallpaperFlags);
7023 }
7024 }
7025}
7026
7027sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7028 const sp<WindowInfoHandle>& windowHandle) const {
7029 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7030 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7031 bool foundWindow = false;
7032 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7033 if (!foundWindow && otherHandle != windowHandle) {
7034 continue;
7035 }
7036 if (windowHandle == otherHandle) {
7037 foundWindow = true;
7038 continue;
7039 }
7040
7041 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7042 return otherHandle;
7043 }
7044 }
7045 return nullptr;
7046}
7047
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007048void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7049 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007050 std::scoped_lock _l(mLock);
7051
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007052 mConfig.keyRepeatTimeout = timeout.count();
7053 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007054}
7055
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007056bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7057 DeviceId deviceId, int32_t pointerId) {
7058 std::scoped_lock _l(mLock);
7059 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7060 if (touchStateIt == mTouchStatesByDisplay.end()) {
7061 return false;
7062 }
7063 for (const TouchedWindow& window : touchStateIt->second.windows) {
7064 if (window.windowHandle->getToken() == token &&
7065 (window.hasTouchingPointer(deviceId, pointerId) ||
7066 window.hasHoveringPointer(deviceId, pointerId))) {
7067 return true;
7068 }
7069 }
7070 return false;
7071}
7072
Garfield Tane84e6f92019-08-29 17:28:41 -07007073} // namespace android::inputdispatcher