blob: 8e75c42c3ce89d6f0fe2d052cd458c5d52584534 [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) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000659 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700660
661 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
662 // ACTION_SCROLL events should not affect the hovering pointer dispatch
663 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000664 }
Linnan Li41859c42024-03-05 16:20:34 +0000665 std::vector<TouchedWindow> out;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000666
667 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800668 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000669
670 std::set<sp<WindowInfoHandle>> oldWindows;
671 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800672 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000673 }
674
675 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800676 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677
678 // If the pointer is no longer in the new window set, send HOVER_EXIT.
679 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
680 if (newWindows.find(oldWindow) == newWindows.end()) {
681 TouchedWindow touchedWindow;
682 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000683 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 out.push_back(touchedWindow);
685 }
686 }
687
688 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
689 TouchedWindow touchedWindow;
690 touchedWindow.windowHandle = newWindow;
691 if (oldWindows.find(newWindow) == oldWindows.end()) {
692 // Any windows that have this pointer now, and didn't have it before, should get
693 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000694 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000695 } else {
696 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700697 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700698 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000699 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
700 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700701 // The Accessibility injected touch exploration event stream
702 // has known inconsistencies, so log ERROR instead of
703 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700704 severity = android::base::LogSeverity::ERROR;
705 }
706 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700707 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000708 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000709 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800710 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000711 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
712 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
713 }
714 out.push_back(touchedWindow);
715 }
716 return out;
717}
718
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800719template <typename T>
720std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
721 left.insert(left.end(), right.begin(), right.end());
722 return left;
723}
724
Harry Cuttsb166c002023-05-09 13:06:05 +0000725// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
726// both.
727void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
728 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
729 if (!window.windowHandle->getInfo()->inputConfig.test(
730 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
731 // In addition to TouchState, erase this window from the input targets! We don't have a
732 // good way to do this today except by adding a nested loop.
733 // TODO(b/282025641): simplify this code once InputTargets are being identified
734 // separately from TouchedWindows.
735 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800736 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000737 });
738 return true;
739 }
740 return false;
741 });
742}
743
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700744/**
745 * In general, touch should be always split between windows. Some exceptions:
746 * 1. Don't split touch if all of the below is true:
747 * (a) we have an active pointer down *and*
748 * (b) a new pointer is going down that's from the same device *and*
749 * (c) the window that's receiving the current pointer does not support split touch.
750 * 2. Don't split mouse events
751 */
752bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
753 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
754 // We should never split mouse events
755 return false;
756 }
757 for (const TouchedWindow& touchedWindow : touchState.windows) {
758 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
759 // Spy windows should not affect whether or not touch is split.
760 continue;
761 }
762 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
763 continue;
764 }
765 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
766 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
767 // Wallpaper window should not affect whether or not touch is split
768 continue;
769 }
770
771 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
772 return false;
773 }
774 }
775 return true;
776}
777
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700778/**
779 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
780 */
781bool isStylusActiveInDisplay(
782 int32_t displayId,
783 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
784 const auto it = touchStatesByDisplay.find(displayId);
785 if (it == touchStatesByDisplay.end()) {
786 return false;
787 }
788 const TouchState& state = it->second;
789 return state.hasActiveStylus();
790}
791
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800792Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
793 struct HashFunction {
794 size_t operator()(const WindowInfo& info) const { return info.id; }
795 };
796
797 std::unordered_set<WindowInfo, HashFunction> windowSet;
798 for (const WindowInfo& info : update.windowInfos) {
799 const auto [_, inserted] = windowSet.insert(info);
800 if (!inserted) {
801 return Error() << "Duplicate entry for " << info;
802 }
803 }
804 return {};
805}
806
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800807int32_t getUserActivityEventType(const EventEntry& eventEntry) {
808 switch (eventEntry.type) {
809 case EventEntry::Type::KEY: {
810 return USER_ACTIVITY_EVENT_BUTTON;
811 }
812 case EventEntry::Type::MOTION: {
813 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
814 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
815 return USER_ACTIVITY_EVENT_TOUCH;
816 }
817 return USER_ACTIVITY_EVENT_OTHER;
818 }
819 default: {
820 LOG_ALWAYS_FATAL("%s events are not user activity",
821 ftl::enum_string(eventEntry.type).c_str());
822 }
823 }
824}
825
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000826std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
827 CancelationOptions::Mode mode) {
828 switch (mode) {
829 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
830 return {true, true};
831 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
832 return {true, false};
833 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
834 return {false, true};
835 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
836 return {false, true};
837 }
838}
839
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000840} // namespace
841
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842// --- InputDispatcher ---
843
Prabir Pradhana41d2442023-04-20 21:30:40 +0000844InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhanbb7a0202024-02-10 02:09:01 +0000845 : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000846
847InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
848 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700849 : mPolicy(policy),
850 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800852 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800853 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700854 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800855 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700856 mDispatchEnabled(false),
857 mDispatchFrozen(false),
858 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100859 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000860 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800861 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000862 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000863 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700864 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800865 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700867 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700868#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700869 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700870#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700871 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000872
873 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000874 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000875 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800876
877 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
880InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000881 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882
Prabir Pradhancef936d2021-07-21 16:17:52 +0000883 resetKeyRepeatLocked();
884 releasePendingEventLocked();
885 drainInboundQueueLocked();
886 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000888 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700889 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800890 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892}
893
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700894status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700895 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700896 return ALREADY_EXISTS;
897 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700898 mThread = std::make_unique<InputThread>(
899 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
900 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700901}
902
903status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700904 if (mThread && mThread->isCallingThread()) {
905 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700906 return INVALID_OPERATION;
907 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700908 mThread.reset();
909 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700910}
911
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700913 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800915 std::scoped_lock _l(mLock);
916 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917
918 // Run a dispatch loop if there are no pending commands.
919 // The dispatch loop might enqueue commands to run afterwards.
920 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800921 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923
924 // Run all pending commands if there are any.
925 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000926 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700927 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 // If we are still waiting for ack on some events,
931 // we might have to wake up earlier to check if an app is anr'ing.
932 const nsecs_t nextAnrCheck = processAnrsLocked();
933 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
934
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800935 // We are about to enter an infinitely long sleep, because we have no commands or
936 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700937 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800938 mDispatcherEnteredIdle.notify_all();
939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 } // release lock
941
942 // Wait for callback or timeout or wake. (make sure we round up, not down)
943 nsecs_t currentTime = now();
944 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
945 mLooper->pollOnce(timeoutMillis);
946}
947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500949 * Raise ANR if there is no focused window.
950 * Before the ANR is raised, do a final state check:
951 * 1. The currently focused application must be the same one we are waiting for.
952 * 2. Ensure we still don't have a focused window.
953 */
954void InputDispatcher::processNoFocusedWindowAnrLocked() {
955 // Check if the application that we are waiting for is still focused.
956 std::shared_ptr<InputApplicationHandle> focusedApplication =
957 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
958 if (focusedApplication == nullptr ||
959 focusedApplication->getApplicationToken() !=
960 mAwaitedFocusedApplication->getApplicationToken()) {
961 // Unexpected because we should have reset the ANR timer when focused application changed
962 ALOGE("Waited for a focused window, but focused application has already changed to %s",
963 focusedApplication->getName().c_str());
964 return; // The focused application has changed.
965 }
966
chaviw98318de2021-05-19 16:45:23 -0500967 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500968 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
969 if (focusedWindowHandle != nullptr) {
970 return; // We now have a focused window. No need for ANR.
971 }
972 onAnrLocked(mAwaitedFocusedApplication);
973}
974
975/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700976 * Check if any of the connections' wait queues have events that are too old.
977 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
978 * Return the time at which we should wake up next.
979 */
980nsecs_t InputDispatcher::processAnrsLocked() {
981 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700982 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700983 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
984 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
985 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500986 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700987 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500988 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700989 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700990 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500991 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
993 }
994 }
995
996 // Check if any connection ANRs are due
997 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
998 if (currentTime < nextAnrCheck) { // most likely scenario
999 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
1000 }
1001
1002 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001003 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 if (connection == nullptr) {
1005 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
1006 return nextAnrCheck;
1007 }
1008 connection->responsive = false;
1009 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001010 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001011 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001012 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001013}
1014
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001015std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001016 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001017 if (connection->monitor) {
1018 return mMonitorDispatchingTimeout;
1019 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001020 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001021 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001022 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001023 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001024 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025}
1026
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001027void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 nsecs_t currentTime = now();
1029
Jeff Browndc5992e2014-04-11 01:27:26 -07001030 // Reset the key repeat timer whenever normal dispatch is suspended while the
1031 // device is in a non-interactive state. This is to ensure that we abort a key
1032 // repeat if the device is just coming out of sleep.
1033 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 resetKeyRepeatLocked();
1035 }
1036
1037 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1038 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001039 if (DEBUG_FOCUS) {
1040 ALOGD("Dispatch frozen. Waiting some more.");
1041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 return;
1043 }
1044
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 // Ready to start a new event.
1046 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 // Synthesize a key repeat if appropriate.
1050 if (mKeyRepeatState.lastKeyEntry) {
1051 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1052 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1053 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001054 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
1057
1058 // Nothing to do if there is no pending event.
1059 if (!mPendingEvent) {
1060 return;
1061 }
1062 } else {
1063 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 mPendingEvent = mInboundQueue.front();
1065 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 traceInboundQueueLengthLocked();
1067 }
1068
1069 // Poke user activity for this event.
1070 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001071 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074
1075 // Now we have an event to dispatch.
1076 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085
1086 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089
1090 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001091 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 const ConfigurationChangedEntry& typedEntry =
1093 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 break;
1097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001099 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const DeviceResetEntry& typedEntry =
1101 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 break;
1105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001107 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const FocusEntry> typedEntry =
1109 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001110 dispatchFocusLocked(currentTime, typedEntry);
1111 done = true;
1112 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1113 break;
1114 }
1115
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001116 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001118 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1119 done = true;
1120 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1121 break;
1122 }
1123
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1125 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001126 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1128 done = true;
1129 break;
1130 }
1131
arthurhungb89ccb02020-12-30 16:19:01 +08001132 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const DragEntry> typedEntry =
1134 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001135 dispatchDragLocked(currentTime, typedEntry);
1136 done = true;
1137 break;
1138 }
1139
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001141 std::shared_ptr<const KeyEntry> keyEntry =
1142 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1147 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001150 if (done && mTracer) {
1151 ensureEventTraced(*keyEntry);
1152 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1153 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 break;
1155 }
1156
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001158 std::shared_ptr<const MotionEntry> motionEntry =
1159 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001161 // The event is stale. However, only drop stale events if there isn't an ongoing
1162 // gesture. That would allow us to complete the processing of the current stroke.
1163 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1164 if (touchStateIt != mTouchStatesByDisplay.end()) {
1165 const TouchState& touchState = touchStateIt->second;
1166 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1167 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1168 dropReason = DropReason::STALE;
1169 }
1170 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001171 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001172 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001173 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1174 // Only drop events that are focus-dispatched.
1175 dropReason = DropReason::BLOCKED;
1176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001178 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001179 if (done && mTracer) {
1180 ensureEventTraced(*motionEntry);
1181 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1182 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
Chris Yef59a2f42020-10-16 12:55:26 -07001185
1186 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001187 std::shared_ptr<const SensorEntry> sensorEntry =
1188 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001189
Chris Yef59a2f42020-10-16 12:55:26 -07001190 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1191 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1192 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1193 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1194 dropReason = DropReason::STALE;
1195 }
1196 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1197 done = true;
1198 break;
1199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201
1202 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001203 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
Michael Wright3a981722015-06-10 15:26:13 +01001206 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
1208 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001209 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
1211}
1212
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001213bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001214 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001215}
1216
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001217/**
1218 * Return true if the events preceding this incoming motion event should be dropped
1219 * Return false otherwise (the default behaviour)
1220 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001221bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001222 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001223 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224
1225 // Optimize case where the current application is unresponsive and the user
1226 // decides to touch a window in a different application.
1227 // If the application takes too long to catch up then we drop all events preceding
1228 // the touch into the other window.
1229 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001230 const int32_t displayId = motionEntry.displayId;
1231 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001232 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001233
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001234 sp<WindowInfoHandle> touchedWindowHandle =
1235 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001236 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001237 touchedWindowHandle->getApplicationToken() !=
1238 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001239 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 ALOGI("Pruning input queue because user touched a different application while waiting "
1241 "for %s",
1242 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001243 return true;
1244 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001245
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001246 // Alternatively, maybe there's a spy window that could handle this event.
1247 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1248 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1249 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001250 const std::shared_ptr<Connection> connection =
1251 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001252 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001253 // This spy window could take more input. Drop all events preceding this
1254 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001255 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001256 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001257 mAwaitedFocusedApplication->getName().c_str());
1258 return true;
1259 }
1260 }
1261 }
1262
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001263 return false;
1264}
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001267 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001269 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 traceInboundQueueLengthLocked();
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001273 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001274 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1275 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001278 if (mTracer) {
1279 ensureEventTraced(keyEntry);
1280 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001281
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001282 // If a new up event comes in, and the pending event with same key code has been asked
1283 // to try again later because of the policy. We have to reset the intercept key wake up
1284 // time for it may have been handled in the policy and could be dropped.
1285 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1286 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001287 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001288 if (pendingKey.keyCode == keyEntry.keyCode &&
1289 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001290 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1291 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001292 pendingKey.interceptKeyWakeupTime = 0;
1293 needWake = true;
1294 }
1295 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 break;
1297 }
1298
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001299 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001300 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1301 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001302 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1303 if (mTracer) {
1304 ensureEventTraced(motionEntry);
1305 }
1306 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001310
1311 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1312 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1313 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1314 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1315 // and some other events have not yet been processed, the dispatcher will wait for
1316 // these events to be processed before dispatching the key event. This is because
1317 // the unprocessed events may cause the focus to change (for example, by launching a
1318 // new window or tapping a different window). To prevent waiting too long, we force
1319 // the key to be sent to the currently focused window when a new tap comes in.
1320 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1321 "just send the pending key event to the currently focused window.");
1322 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001323 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001324 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001327 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001328 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1329 break;
1330 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001331 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001332 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001333 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001334 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001335 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1336 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001337 // nothing to do
1338 break;
1339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341
1342 return needWake;
1343}
1344
Prabir Pradhan24047542023-11-02 17:14:59 +00001345void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001346 // Do not store sensor event in recent queue to avoid flooding the queue.
1347 if (entry->type != EventEntry::Type::SENSOR) {
1348 mRecentQueue.push_back(entry);
1349 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001350 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001351 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001355sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1356 bool isStylus,
1357 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001359 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001360 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001361 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001362 continue;
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001365 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001366 if (!info.isSpy() &&
1367 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 return windowHandle;
1369 }
1370 }
1371 return nullptr;
1372}
1373
1374std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001375 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001376 if (touchedWindow == nullptr) {
1377 return {};
1378 }
1379 // Traverse windows from front to back until we encounter the touched window.
1380 std::vector<InputTarget> outsideTargets;
1381 const auto& windowHandles = getWindowHandlesLocked(displayId);
1382 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1383 if (windowHandle == touchedWindow) {
1384 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1385 // below the touched window will not get ACTION_OUTSIDE event.
1386 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001387 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001388
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001389 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001390 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001391 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1392 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001393 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1394 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001395 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
1397 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001398 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399}
1400
Prabir Pradhand65552b2021-10-07 11:23:50 -07001401std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001402 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001403 // Traverse windows from front to back and gather the touched spy windows.
1404 std::vector<sp<WindowInfoHandle>> spyWindows;
1405 const auto& windowHandles = getWindowHandlesLocked(displayId);
1406 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1407 const WindowInfo& info = *windowHandle->getInfo();
1408
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001409 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001410 continue;
1411 }
1412 if (!info.isSpy()) {
1413 // The first touched non-spy window was found, so return the spy windows touched so far.
1414 return spyWindows;
1415 }
1416 spyWindows.push_back(windowHandle);
1417 }
1418 return spyWindows;
1419}
1420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 const char* reason;
1423 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001424 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001425 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001426 ALOGD("Dropped event because policy consumed it.");
1427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 reason = "inbound event was dropped because the policy consumed it";
1429 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001430 case DropReason::DISABLED:
1431 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 ALOGI("Dropped event because input dispatch is disabled.");
1433 }
1434 reason = "inbound event was dropped because input dispatch is disabled";
1435 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001436 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001437 LOG(INFO) << "Dropping because the current application is not responding and the user "
1438 "has started interacting with a different application: "
1439 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 reason = "inbound event was dropped because the current application is not responding "
1441 "and the user has started interacting with a different application";
1442 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001443 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 ALOGI("Dropped event because it is stale.");
1445 reason = "inbound event was dropped because it is stale";
1446 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001447 case DropReason::NO_POINTER_CAPTURE:
1448 ALOGI("Dropped event because there is no window with Pointer Capture.");
1449 reason = "inbound event was dropped because there is no window with Pointer Capture";
1450 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001451 case DropReason::NOT_DROPPED: {
1452 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 }
1456
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001458 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001459 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001460 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1461 options.displayId = keyEntry.displayId;
1462 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001466 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001467 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1468 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001469 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001470 options.displayId = motionEntry.displayId;
1471 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 synthesizeCancelationEventsForAllConnectionsLocked(options);
1473 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001474 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1475 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001476 options.displayId = motionEntry.displayId;
1477 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 synthesizeCancelationEventsForAllConnectionsLocked(options);
1479 }
1480 break;
1481 }
Chris Yef59a2f42020-10-16 12:55:26 -07001482 case EventEntry::Type::SENSOR: {
1483 break;
1484 }
arthurhungb89ccb02020-12-30 16:19:01 +08001485 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1486 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001487 break;
1488 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001489 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001490 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001491 case EventEntry::Type::CONFIGURATION_CHANGED:
1492 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001493 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001494 break;
1495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497}
1498
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001500 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501}
1502
Prabir Pradhancef936d2021-07-21 16:17:52 +00001503bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001504 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return false;
1506 }
1507
1508 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001509 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001510 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001511 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1512 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001513 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 return true;
1515}
1516
Prabir Pradhancef936d2021-07-21 16:17:52 +00001517void InputDispatcher::postCommandLocked(Command&& command) {
1518 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
1521void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001522 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001523 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001524 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 releaseInboundEventLocked(entry);
1526 }
1527 traceInboundQueueLengthLocked();
1528}
1529
1530void InputDispatcher::releasePendingEventLocked() {
1531 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001533 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535}
1536
Prabir Pradhan24047542023-11-02 17:14:59 +00001537void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001538 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001540 if (DEBUG_DISPATCH_CYCLE) {
1541 ALOGD("Injected inbound event was dropped.");
1542 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001543 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001546 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549}
1550
1551void InputDispatcher::resetKeyRepeatLocked() {
1552 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001553 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
1555}
1556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001557std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001558 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559
Michael Wright2e732952014-09-24 13:26:59 -07001560 uint32_t policyFlags = entry->policyFlags &
1561 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001564 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1565 currentTime, entry->deviceId, entry->source,
1566 entry->displayId, policyFlags, entry->action, entry->flags,
1567 entry->keyCode, entry->scanCode, entry->metaState,
1568 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001570 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001571 if (mTracer) {
1572 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1573 }
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578}
1579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
1586 // Reset key repeating in case a keyboard device was added or removed or something.
1587 resetKeyRepeatLocked();
1588
1589 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001590 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1591 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001592 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001593 };
1594 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 return true;
1596}
1597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001598bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1599 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1601 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1602 entry.deviceId);
1603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
liushenxiang42232912021-05-21 20:24:09 +08001605 // Reset key repeating in case a keyboard device was disabled or enabled.
1606 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1607 resetKeyRepeatLocked();
1608 }
1609
Michael Wrightfb04fd52022-11-24 22:31:11 +00001610 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001611 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001613
1614 // Remove all active pointers from this device
1615 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1616 touchState.removeAllPointersForDevice(entry.deviceId);
1617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 return true;
1619}
1620
Vishnu Nairad321cd2020-08-20 16:40:21 -07001621void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001622 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001623 if (mPendingEvent != nullptr) {
1624 // Move the pending event to the front of the queue. This will give the chance
1625 // for the pending event to get dispatched to the newly focused window
1626 mInboundQueue.push_front(mPendingEvent);
1627 mPendingEvent = nullptr;
1628 }
1629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001630 std::unique_ptr<FocusEntry> focusEntry =
1631 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1632 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001633
1634 // This event should go to the front of the queue, but behind all other focus events
1635 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001636 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1637 [](const std::shared_ptr<const EventEntry>& event) {
1638 return event->type == EventEntry::Type::FOCUS;
1639 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001640
1641 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001643}
1644
Prabir Pradhan24047542023-11-02 17:14:59 +00001645void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1646 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001647 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1648 if (connection == nullptr) {
1649 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001650 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001651 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001652 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001653 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001654 std::string reason = std::string("reason=").append(entry->reason);
1655 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001656 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001657}
1658
Prabir Pradhan99987712020-11-10 18:43:05 -08001659void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001660 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001661 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 dropReason = DropReason::NOT_DROPPED;
1663
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001666
1667 if (entry->pointerCaptureRequest.enable) {
1668 // Enable Pointer Capture.
1669 if (haveWindowWithPointerCapture &&
1670 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001671 // This can happen if pointer capture is disabled and re-enabled before we notify the
1672 // app of the state change, so there is no need to notify the app.
1673 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1674 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001675 }
1676 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001677 // This can happen if a window requests capture and immediately releases capture.
1678 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001679 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001680 return;
1681 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001682 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1683 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1684 return;
1685 }
1686
Vishnu Nairc519ff72021-01-21 08:23:08 -08001687 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001688 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1689 mWindowTokenWithPointerCapture = token;
1690 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001691 // Disable Pointer Capture.
1692 // We do not check if the sequence number matches for requests to disable Pointer Capture
1693 // for two reasons:
1694 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1695 // to disable capture with the same sequence number: one generated by
1696 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1697 // Capture being disabled in InputReader.
1698 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1699 // actual Pointer Capture state that affects events being generated by input devices is
1700 // in InputReader.
1701 if (!haveWindowWithPointerCapture) {
1702 // Pointer capture was already forcefully disabled because of focus change.
1703 dropReason = DropReason::NOT_DROPPED;
1704 return;
1705 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001706 token = mWindowTokenWithPointerCapture;
1707 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001708 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001709 setPointerCaptureLocked(false);
1710 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001711 }
1712
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001713 auto connection = getConnectionLocked(token);
1714 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001715 // Window has gone away, clean up Pointer Capture state.
1716 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001717 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001718 setPointerCaptureLocked(false);
1719 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001720 return;
1721 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001722 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001723 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001724
1725 dropReason = DropReason::NOT_DROPPED;
1726}
1727
Prabir Pradhan24047542023-11-02 17:14:59 +00001728void InputDispatcher::dispatchTouchModeChangeLocked(
1729 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001730 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001731 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001732 if (windowHandles.empty()) {
1733 return;
1734 }
1735 const std::vector<InputTarget> inputTargets =
1736 getInputTargetsFromWindowHandlesLocked(windowHandles);
1737 if (inputTargets.empty()) {
1738 return;
1739 }
1740 entry->dispatchInProgress = true;
1741 dispatchEventLocked(currentTime, entry, inputTargets);
1742}
1743
1744std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1745 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1746 std::vector<InputTarget> inputTargets;
1747 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001748 const sp<IBinder>& token = handle->getToken();
1749 if (token == nullptr) {
1750 continue;
1751 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001752 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1753 if (connection == nullptr) {
1754 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001755 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001756 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001757 }
1758 return inputTargets;
1759}
1760
Prabir Pradhan24047542023-11-02 17:14:59 +00001761bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001762 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001764 if (!entry->dispatchInProgress) {
1765 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1766 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1767 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1768 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001769 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 // We have seen two identical key downs in a row which indicates that the device
1771 // driver is automatically generating key repeats itself. We take note of the
1772 // repeat here, but we disable our own next key repeat timer since it is clear that
1773 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001774 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1775 // Make sure we don't get key down from a different device. If a different
1776 // device Id has same key pressed down, the new device Id will replace the
1777 // current one to hold the key repeat with repeat count reset.
1778 // In the future when got a KEY_UP on the device id, drop it and do not
1779 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1781 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001782 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 } else {
1784 // Not a repeat. Save key down state in case we do see a repeat later.
1785 resetKeyRepeatLocked();
1786 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1787 }
1788 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001789 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1790 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001791 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001792 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001793 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1794 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 resetKeyRepeatLocked();
1797 }
1798
1799 if (entry->repeatCount == 1) {
1800 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1801 } else {
1802 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1803 }
1804
1805 entry->dispatchInProgress = true;
1806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001807 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809
1810 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001811 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001813 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 return false; // wait until next wakeup
1815 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001816 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 entry->interceptKeyWakeupTime = 0;
1818 }
1819
1820 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001821 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001823 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001824 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001825
1826 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1827 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1828 };
1829 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001830 // Poke user activity for keys not passed to user
1831 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 return false; // wait for the command to run
1833 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001834 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001836 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001837 if (*dropReason == DropReason::NOT_DROPPED) {
1838 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840 }
1841
1842 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001843 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001844 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001845 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1846 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001847 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001848 // Poke user activity for undispatched keys
1849 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return true;
1851 }
1852
1853 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 InputEventInjectionResult injectionResult;
1855 sp<WindowInfoHandle> focusedWindow =
1856 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1857 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return false;
1860 }
1861
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001862 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 return true;
1865 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001866 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1867
1868 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001869 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1870 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001872 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001873 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001875 if (mTracer) {
1876 ensureEventTraced(*entry);
1877 for (const auto& target : inputTargets) {
1878 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1879 }
1880 }
1881
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 // Dispatch the key.
1883 dispatchEventLocked(currentTime, entry, inputTargets);
1884 return true;
1885}
1886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001888 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1889 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1890 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1891 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1892 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1893 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1894 entry.metaState, entry.repeatCount, entry.downTime);
1895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896}
1897
Prabir Pradhancef936d2021-07-21 16:17:52 +00001898void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001899 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001900 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001901 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1902 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1903 "source=0x%x, sensorType=%s",
1904 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001905 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001907 auto command = [this, entry]() REQUIRES(mLock) {
1908 scoped_unlock unlock(mLock);
1909
1910 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001911 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001912 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001913 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1914 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001915 };
1916 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001917}
1918
1919bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001920 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1921 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001922 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001923 }
Chris Yef59a2f42020-10-16 12:55:26 -07001924 { // acquire lock
1925 std::scoped_lock _l(mLock);
1926
1927 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001928 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001929 if (entry->type == EventEntry::Type::SENSOR) {
1930 it = mInboundQueue.erase(it);
1931 releaseInboundEventLocked(entry);
1932 }
1933 }
1934 }
1935 return true;
1936}
1937
Prabir Pradhan24047542023-11-02 17:14:59 +00001938bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1939 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001940 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 entry->dispatchInProgress = true;
1945
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948
1949 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001950 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001951 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001952 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1953 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 return true;
1955 }
1956
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001957 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
1959 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001960 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 if (isPointerEvent) {
1964 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001965
1966 if (mDragState &&
1967 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1968 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1969 pilferPointersLocked(mDragState->dragWindow->getToken());
1970 }
1971
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001972 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001973 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001974 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1975 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 } else {
1977 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978 sp<WindowInfoHandle> focusedWindow =
1979 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1980 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1981 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001982 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1983 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1984 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 return false;
1989 }
1990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001991 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001992 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001993 return true;
1994 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001995 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001996 CancelationOptions::Mode mode(
1997 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1998 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001999 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00002000 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002001 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 return true;
2003 }
2004
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002005 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002006 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002008 if (mTracer) {
2009 ensureEventTraced(*entry);
2010 for (const auto& target : inputTargets) {
2011 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2012 }
2013 }
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 dispatchEventLocked(currentTime, entry, inputTargets);
2017 return true;
2018}
2019
chaviw98318de2021-05-19 16:45:23 -05002020void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002021 bool isExiting, const int32_t rawX,
2022 const int32_t rawY) {
2023 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002024 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002025 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2026 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002027
2028 enqueueInboundEventLocked(std::move(dragEntry));
2029}
2030
Prabir Pradhan24047542023-11-02 17:14:59 +00002031void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2032 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002033 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2034 if (connection == nullptr) {
2035 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002036 }
arthurhungb89ccb02020-12-30 16:19:01 +08002037 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002038 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002039}
2040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002041void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002042 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002043 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002044 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002045 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002046 "metaState=0x%x, buttonState=0x%x,"
2047 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002048 prefix, entry.eventTime, entry.deviceId,
2049 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2050 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2051 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2052 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002054 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002055 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002056 "x=%f, y=%f, pressure=%f, size=%f, "
2057 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2058 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002059 i, entry.pointerProperties[i].id,
2060 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002061 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2062 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2063 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2064 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2065 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2066 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2067 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2068 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2069 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072}
2073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002074void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002075 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002078 if (DEBUG_DISPATCH_CYCLE) {
2079 ALOGD("dispatchEventToCurrentInputTargets");
2080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002082 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002083
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002088 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002089 std::shared_ptr<Connection> connection = inputTarget.connection;
2090 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092}
2093
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002094void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2096 // If the policy decides to close the app, we will get a channel removal event via
2097 // unregisterInputChannel, and will clean up the connection that way. We are already not
2098 // sending new pointers to the connection when it blocked, but focused events will continue to
2099 // pile up.
2100 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002101 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002102 if (connection->status != Connection::Status::NORMAL) {
2103 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002105 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2106 "application not responding");
2107
2108 sp<WindowInfoHandle> windowHandle;
2109 if (!connection->monitor) {
2110 windowHandle = getWindowHandleLocked(connection->getToken());
2111 if (windowHandle == nullptr) {
2112 // The window that is receiving this ANR was removed, so there is no need to generate
2113 // cancellations, because the cancellations would have already been generated when
2114 // the window was removed.
2115 return;
2116 }
2117 }
2118 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119}
2120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002122 if (DEBUG_FOCUS) {
2123 ALOGD("Resetting ANR timeouts.");
2124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002128 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129}
2130
Tiger Huang721e26f2018-07-24 22:26:19 +08002131/**
2132 * Get the display id that the given event should go to. If this event specifies a valid display id,
2133 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2134 * Focused display is the display that the user most recently interacted with.
2135 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002136int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002137 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002138 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002139 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002140 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2141 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 break;
2143 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002144 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2146 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 break;
2148 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002149 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002150 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002151 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002152 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002153 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002154 case EventEntry::Type::SENSOR:
2155 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002156 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 return ADISPLAY_ID_NONE;
2158 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002159 }
2160 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2161}
2162
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2164 const char* focusedWindowName) {
2165 if (mAnrTracker.empty()) {
2166 // already processed all events that we waited for
2167 mKeyIsWaitingForEventsTimeout = std::nullopt;
2168 return false;
2169 }
2170
2171 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2172 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002173 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002174 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002175 std::chrono::duration_cast<std::chrono::nanoseconds>(
2176 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002177 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 return true;
2179 }
2180
2181 // We still have pending events, and already started the timer
2182 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2183 return true; // Still waiting
2184 }
2185
2186 // Waited too long, and some connection still hasn't processed all motions
2187 // Just send the key to the focused window
2188 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2189 focusedWindowName);
2190 mKeyIsWaitingForEventsTimeout = std::nullopt;
2191 return false;
2192}
2193
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002194sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002195 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198
Tiger Huang721e26f2018-07-24 22:26:19 +08002199 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002200 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002201 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002202 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2203
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 // If there is no currently focused window and no focused application
2205 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2207 ALOGI("Dropping %s event because there is no focused window or focused application in "
2208 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002209 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002210 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
Vishnu Nair062a8672021-09-03 16:07:44 -07002213 // Drop key events if requested by input feature
2214 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002215 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002216 }
2217
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002218 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2219 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2220 // start interacting with another application via touch (app switch). This code can be removed
2221 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2222 // an app is expected to have a focused window.
2223 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2224 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2225 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002226 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2227 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2228 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002230 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002231 ALOGW("Waiting because no window has focus but %s may eventually add a "
2232 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002233 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002234 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::PENDING;
2236 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2238 // Already raised ANR. Drop the event
2239 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002240 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002241 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 } else {
2243 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002244 outInjectionResult = InputEventInjectionResult::PENDING;
2245 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 }
2247 }
2248
2249 // we have a valid, non-null focused window
2250 resetNoFocusedWindowTimeoutLocked();
2251
Prabir Pradhan5735a322022-04-11 17:23:34 +00002252 // Verify targeted injection.
2253 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2254 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002255 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2256 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002259 if (focusedWindowHandle->getInfo()->inputConfig.test(
2260 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002261 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::PENDING;
2263 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 }
2265
2266 // If the event is a key event, then we must wait for all previous events to
2267 // complete before delivering it because previous events may have the
2268 // side-effect of transferring focus to a different window and we want to
2269 // ensure that the following keys are sent to the new window.
2270 //
2271 // Suppose the user touches a button in a window then immediately presses "A".
2272 // If the button causes a pop-up window to appear then we want to ensure that
2273 // the "A" key is delivered to the new pop-up window. This is because users
2274 // often anticipate pending UI changes when typing on a keyboard.
2275 // To obtain this behavior, we must serialize key events with respect to all
2276 // prior input events.
2277 if (entry.type == EventEntry::Type::KEY) {
2278 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002279 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002280 outInjectionResult = InputEventInjectionResult::PENDING;
2281 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002285 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2286 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287}
2288
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002289/**
2290 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2291 * that are currently unresponsive.
2292 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002293std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2294 const std::vector<Monitor>& monitors) const {
2295 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002296 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002297 [](const Monitor& monitor) REQUIRES(mLock) {
2298 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002299 if (!connection->responsive) {
2300 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002301 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002302 return false;
2303 }
2304 return true;
2305 });
2306 return responsiveMonitors;
2307}
2308
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002309std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002310 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002311 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002312 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002314 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 // For security reasons, we defer updating the touch state until we are sure that
2316 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 const int32_t displayId = entry.displayId;
2318 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002319 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320
2321 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002322 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 // Copy current touch state into tempTouchState.
2325 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2326 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002327 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002328 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2330 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002331 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002332 }
2333
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002334 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002335
2336 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2337 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2338 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002339 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2340 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002341 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002342 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2343 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002344 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2345 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2346 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002347 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002348
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002349 if (newGesture) {
2350 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002351 }
2352
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002353 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2354 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2355 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002358 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002359 if (wasDown) {
2360 // Started hovering, but the device is already down: reject the hover event
2361 LOG(ERROR) << "Got hover event " << entry.getDescription()
2362 << " but the device is already down " << oldState->dump();
2363 outInjectionResult = InputEventInjectionResult::FAILED;
2364 return {};
2365 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002366 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2367 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002368 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002369 }
2370
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2372 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002373 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002374 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002375 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002376 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2377 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002378 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002379 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002380 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002381
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002382 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002383 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002386 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002387 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002390 }
2391
Prabir Pradhan5735a322022-04-11 17:23:34 +00002392 // Verify targeted injection.
2393 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2394 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002395 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002396 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002397 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002398 }
2399
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002401 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2403 // New window supports splitting, but we should never split mouse events.
2404 isSplit = !isFromMouse;
2405 } else if (isSplit) {
2406 // New window does not support splitting but we have already split events.
2407 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002408 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2409 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002410 newTouchedWindowHandle = nullptr;
2411 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 } else {
2413 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002414 // be delivered to a new window which supports split touch. Pointers from a mouse device
2415 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002416 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002417 }
2418
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002419 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002420 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002422 // Process the foreground window first so that it is the first to receive the event.
2423 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 }
2425
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002426 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002427 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2428 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002429 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002430 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002431 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002432 }
2433
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002435 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 continue;
2437 }
2438
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002439 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002440 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002441 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002442 }
2443
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002444 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002445 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002446
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002447 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2448 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002450 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002451
2452 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002453 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 }
2455 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002456 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002457 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002458 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002459 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002460
2461 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002462
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002463 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002464 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2465 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002466 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002467 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002468 isDownOrPointerDown
2469 ? std::make_optional(entry.eventTime)
2470 : std::nullopt);
2471 // If this is the pointer going down and the touched window has a wallpaper
2472 // then also add the touched wallpaper windows so they are locked in for the
2473 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2474 // SCROLL because the wallpaper engine only supports touch events. We would need to
2475 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2476 // handle these events.
2477 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002478 windowHandle->getInfo()->inputConfig.test(
2479 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2480 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2481 if (wallpaper != nullptr) {
2482 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2483 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002484 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002485 if (isSplit) {
2486 wallpaperFlags |= InputTarget::Flags::SPLIT;
2487 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002488 tempTouchState.addOrUpdateWindow(wallpaper,
2489 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002490 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002491 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002492 }
2493 }
2494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002496
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002497 // If a window is already pilfering some pointers, give it this new pointer as well and
2498 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2499 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002500 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002501 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002502 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002503 // This window is already pilfering some pointers, and this new pointer is also
2504 // going to it. Therefore, take over this pointer and don't give it to anyone
2505 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002506 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002507 }
2508 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002509
2510 // Restrict all pilfered pointers to the pilfering windows.
2511 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 } else {
2513 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2514
2515 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002516 if (!tempTouchState.isDown(entry.deviceId) &&
2517 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002518 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2519 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2520 << " is not down or we previously dropped the pointer down event in "
2521 << "display " << displayId << ": " << entry.getDescription();
2522 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002523 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002524 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002527 // If the pointer is not currently hovering, then ignore the event.
2528 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2529 const int32_t pointerId = entry.pointerProperties[0].id;
2530 if (oldState == nullptr ||
2531 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2532 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2533 "display "
2534 << displayId << ": " << entry.getDescription();
2535 outInjectionResult = InputEventInjectionResult::FAILED;
2536 return {};
2537 }
2538 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2539 }
2540
arthurhung6d4bed92021-03-17 11:59:33 +08002541 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002542
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002544 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002545 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002546 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002547 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002548 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002549 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002550 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002551 sp<WindowInfoHandle> newTouchedWindowHandle =
2552 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002553
Prabir Pradhan5735a322022-04-11 17:23:34 +00002554 // Verify targeted injection.
2555 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2556 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002557 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002558 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002559 }
2560
Linnan Libf069a32024-02-29 17:22:59 +00002561 // Do not slide events to the window which can not receive motion event
Vishnu Nair062a8672021-09-03 16:07:44 -07002562 if (newTouchedWindowHandle != nullptr &&
Linnan Libf069a32024-02-29 17:22:59 +00002563 !canWindowReceiveMotionLocked(newTouchedWindowHandle, entry)) {
Vishnu Nair062a8672021-09-03 16:07:44 -07002564 newTouchedWindowHandle = nullptr;
2565 }
2566
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002567 if (newTouchedWindowHandle != nullptr &&
2568 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002569 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002570 oldTouchedWindowHandle->getName().c_str(),
2571 newTouchedWindowHandle->getName().c_str(), displayId);
2572
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002574 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002575 const PointerProperties& pointer = entry.pointerProperties[0];
2576 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002577
2578 const TouchedWindow& touchedWindow =
2579 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002580 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002581 InputTarget::DispatchMode::SLIPPERY_EXIT,
2582 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002583 touchedWindow.getDownTimeInTarget(entry.deviceId),
2584 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585
2586 // Make a slippery entrance into the new window.
2587 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002588 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002591 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002592 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002593 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002596 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002599 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002600 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002601 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002604 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2605 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002606 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002607 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002608
2609 // Check if the wallpaper window should deliver the corresponding event.
2610 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002611 tempTouchState, entry.deviceId, pointer, targets);
2612 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002613 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615 }
Arthur Hung96483742022-11-15 03:30:48 +00002616
2617 // Update the pointerIds for non-splittable when it received pointer down.
2618 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2619 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002620 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002621 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2622 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002623 // Ignore drag window for it should just track one pointer.
2624 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2625 continue;
2626 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002627 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002628 }
2629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 }
2631
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002632 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002633 {
2634 std::vector<TouchedWindow> hoveringWindows =
2635 getHoveringWindowsLocked(oldState, tempTouchState, entry);
Linnan Li41859c42024-03-05 16:20:34 +00002636 // Hardcode to single hovering pointer for now.
2637 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2638 pointerIds.set(entry.pointerProperties[0].id);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002639 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Linnan Li41859c42024-03-05 16:20:34 +00002640 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2641 touchedWindow.targetFlags, pointerIds,
2642 touchedWindow.getDownTimeInTarget(entry.deviceId),
2643 targets);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646
Prabir Pradhan5735a322022-04-11 17:23:34 +00002647 // Ensure that all touched windows are valid for injection.
2648 if (entry.injectionState != nullptr) {
2649 std::string errs;
2650 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002651 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2652 if (err) errs += "\n - " + *err;
2653 }
2654 if (!errs.empty()) {
2655 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002656 "%s:%s",
2657 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002658 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002659 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002660 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002661 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002662
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2664 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002666 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002667 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002668 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002669 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002670 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002671 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002672 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002673 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002674 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2675 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 }
2678 }
2679 }
2680 }
2681
Harry Cuttsb166c002023-05-09 13:06:05 +00002682 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2683 // only want the system UI to handle these gestures.
2684 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2685 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2686 if (isTouchpadNavGesture) {
2687 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2688 }
2689
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002690 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002691 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002692 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002693 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002694 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002695 continue;
2696 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002697 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002698 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002699 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002700 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002701
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002702 // During targeted injection, only allow owned targets to receive events
2703 std::erase_if(targets, [&](const InputTarget& target) {
2704 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2705 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2706 if (err) {
2707 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2708 << ": " << (*err);
2709 return true;
2710 }
2711 return false;
2712 });
2713
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002714 if (targets.empty()) {
2715 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2716 outInjectionResult = InputEventInjectionResult::FAILED;
2717 return {};
2718 }
2719
2720 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2721 // window that is actually receiving the entire gesture.
2722 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002723 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002724 })) {
2725 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2726 << entry.getDescription();
2727 outInjectionResult = InputEventInjectionResult::FAILED;
2728 return {};
2729 }
2730
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002731 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Prabir Pradhan502a7252023-12-01 16:11:24 +00002733 // Now that we have generated all of the input targets for this event, reset the dispatch
2734 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002735 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002736 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 }
2738
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002739 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002740 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002741 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002742 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002743 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002744 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002745 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002746 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2747 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002748 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2749 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2750 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 }
2752
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002753 // Save changes unless the action was scroll in which case the temporary touch
2754 // state was only valid for this one action.
2755 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002756 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002757 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002758 mTouchStatesByDisplay[displayId] = tempTouchState;
2759 } else {
2760 mTouchStatesByDisplay.erase(displayId);
2761 }
2762 }
2763
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002764 if (tempTouchState.windows.empty()) {
2765 mTouchStatesByDisplay.erase(displayId);
2766 }
2767
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002768 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769}
2770
arthurhung6d4bed92021-03-17 11:59:33 +08002771void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002772 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2773 // have an explicit reason to support it.
2774 constexpr bool isStylus = false;
2775
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002776 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002777 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002778 if (dropWindow) {
2779 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002780 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002781 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002782 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002783 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002784 }
2785 mDragState.reset();
2786}
2787
2788void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002789 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002790 return;
2791 }
2792
arthurhung6d4bed92021-03-17 11:59:33 +08002793 if (!mDragState->isStartDrag) {
2794 mDragState->isStartDrag = true;
2795 mDragState->isStylusButtonDownAtStart =
2796 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2797 }
2798
Arthur Hung54745652022-04-20 07:17:41 +00002799 // Find the pointer index by id.
2800 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002801 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002802 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2803 if (pointerProperties.id == mDragState->pointerId) {
2804 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002805 }
Arthur Hung54745652022-04-20 07:17:41 +00002806 }
arthurhung6d4bed92021-03-17 11:59:33 +08002807
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002808 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002809 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002810 }
2811
2812 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2813 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2814 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2815
2816 switch (maskedAction) {
2817 case AMOTION_EVENT_ACTION_MOVE: {
2818 // Handle the special case : stylus button no longer pressed.
2819 bool isStylusButtonDown =
2820 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2821 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2822 finishDragAndDrop(entry.displayId, x, y);
2823 return;
2824 }
2825
2826 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2827 // until we have an explicit reason to support it.
2828 constexpr bool isStylus = false;
2829
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002830 sp<WindowInfoHandle> hoverWindowHandle =
2831 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2832 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002833 // enqueue drag exit if needed.
2834 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2835 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2836 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002837 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002838 y);
2839 }
2840 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2841 }
2842 // enqueue drag location if needed.
2843 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002844 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002845 }
2846 break;
2847 }
2848
2849 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002850 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002851 break;
2852 }
2853 // The drag pointer is up.
2854 [[fallthrough]];
2855 case AMOTION_EVENT_ACTION_UP:
2856 finishDragAndDrop(entry.displayId, x, y);
2857 break;
2858 case AMOTION_EVENT_ACTION_CANCEL: {
2859 ALOGD("Receiving cancel when drag and drop.");
2860 sendDropWindowCommandLocked(nullptr, 0, 0);
2861 mDragState.reset();
2862 break;
2863 }
arthurhungb89ccb02020-12-30 16:19:01 +08002864 }
2865}
2866
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2868 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002869 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002871 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2872 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002873 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2874 return {};
2875 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002876 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002877 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002878 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002879 inputTarget.flags = targetFlags;
2880 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2881 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2882 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2883 if (displayInfoIt != mDisplayInfos.end()) {
2884 inputTarget.displayTransform = displayInfoIt->second.transform;
2885 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002886 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002887 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2888 }
2889 return inputTarget;
2890}
2891
chaviw98318de2021-05-19 16:45:23 -05002892void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002893 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002894 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002895 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002896 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002897 std::vector<InputTarget>::iterator it =
2898 std::find_if(inputTargets.begin(), inputTargets.end(),
2899 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002900 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002902
chaviw98318de2021-05-19 16:45:23 -05002903 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002904
2905 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002906 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002907 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2908 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002909 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002910 return;
2911 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002912 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002913 it = inputTargets.end() - 1;
2914 }
2915
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002916 if (it->flags != targetFlags) {
2917 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2918 }
2919 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2920 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2921 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2922 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002923}
2924
2925void InputDispatcher::addPointerWindowTargetLocked(
2926 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002927 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2928 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2929 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002930 if (pointerIds.none()) {
2931 for (const auto& target : inputTargets) {
2932 LOG(INFO) << "Target: " << target;
2933 }
2934 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2935 return;
2936 }
2937 std::vector<InputTarget>::iterator it =
2938 std::find_if(inputTargets.begin(), inputTargets.end(),
2939 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002940 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002941 });
2942
2943 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2944 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2945 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2946 // input targets for hovering pointers and for touching pointers.
2947 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2948 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002949 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002950 // Force the code below to create a new input target
2951 it = inputTargets.end();
2952 }
2953
2954 const WindowInfo* windowInfo = windowHandle->getInfo();
2955
2956 if (it == inputTargets.end()) {
2957 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002958 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2959 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002960 if (!target) {
2961 return;
2962 }
2963 inputTargets.push_back(*target);
2964 it = inputTargets.end() - 1;
2965 }
2966
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002967 if (it->dispatchMode != dispatchMode) {
2968 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2969 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2970 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002971 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002972 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2973 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002974 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002975 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002976 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002977 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2978 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002979
chaviw1ff3d1e2020-07-01 15:53:47 -07002980 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981}
2982
Michael Wright3dd60e22019-03-27 22:06:44 +00002983void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002984 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002985 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2986 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002987
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002988 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002989 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002990 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2991 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002992 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2993 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002994 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002995 target.setDefaultPointerTransform(target.displayTransform);
2996 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 }
2998}
2999
Robert Carrc9bf1d32020-04-13 17:21:08 -07003000/**
3001 * Indicate whether one window handle should be considered as obscuring
3002 * another window handle. We only check a few preconditions. Actually
3003 * checking the bounds is left to the caller.
3004 */
chaviw98318de2021-05-19 16:45:23 -05003005static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3006 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003007 // Compare by token so cloned layers aren't counted
3008 if (haveSameToken(windowHandle, otherHandle)) {
3009 return false;
3010 }
3011 auto info = windowHandle->getInfo();
3012 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003013 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003014 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003015 } else if (otherInfo->alpha == 0 &&
3016 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003017 // Those act as if they were invisible, so we don't need to flag them.
3018 // We do want to potentially flag touchable windows even if they have 0
3019 // opacity, since they can consume touches and alter the effects of the
3020 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003021 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003022 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3023 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003024 } else if (info->ownerUid == otherInfo->ownerUid) {
3025 // If ownerUid is the same we don't generate occlusion events as there
3026 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003027 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003028 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003029 return false;
3030 } else if (otherInfo->displayId != info->displayId) {
3031 return false;
3032 }
3033 return true;
3034}
3035
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003036/**
3037 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3038 * untrusted, one should check:
3039 *
3040 * 1. If result.hasBlockingOcclusion is true.
3041 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3042 * BLOCK_UNTRUSTED.
3043 *
3044 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3045 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3046 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3047 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3048 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3049 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3050 *
3051 * If neither of those is true, then it means the touch can be allowed.
3052 */
3053InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003054 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3055 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003056 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003057 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003058 TouchOcclusionInfo info;
3059 info.hasBlockingOcclusion = false;
3060 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003061 info.obscuringUid = gui::Uid::INVALID;
3062 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003063 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003064 if (windowHandle == otherHandle) {
3065 break; // All future windows are below us. Exit early.
3066 }
chaviw98318de2021-05-19 16:45:23 -05003067 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003068 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3069 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003070 if (DEBUG_TOUCH_OCCLUSION) {
3071 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003072 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003073 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003074 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3075 // we perform the checks below to see if the touch can be propagated or not based on the
3076 // window's touch occlusion mode
3077 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3078 info.hasBlockingOcclusion = true;
3079 info.obscuringUid = otherInfo->ownerUid;
3080 info.obscuringPackage = otherInfo->packageName;
3081 break;
3082 }
3083 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003084 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003085 float opacity =
3086 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3087 // Given windows A and B:
3088 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3089 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3090 opacityByUid[uid] = opacity;
3091 if (opacity > info.obscuringOpacity) {
3092 info.obscuringOpacity = opacity;
3093 info.obscuringUid = uid;
3094 info.obscuringPackage = otherInfo->packageName;
3095 }
3096 }
3097 }
3098 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003099 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003100 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003101 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003102 return info;
3103}
3104
chaviw98318de2021-05-19 16:45:23 -05003105std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003106 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003107 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003108 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3109 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3110 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003111 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003112 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003113 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3114 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003115 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3116 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3117 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003118 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003119}
3120
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003121bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3122 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003123 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3124 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003125 return false;
3126 }
3127 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003128 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003129 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003130 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003131 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3132 return false;
3133 }
3134 return true;
3135}
3136
chaviw98318de2021-05-19 16:45:23 -05003137bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003140 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3141 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003142 if (windowHandle == otherHandle) {
3143 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
chaviw98318de2021-05-19 16:45:23 -05003145 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003146 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003147 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 return true;
3149 }
3150 }
3151 return false;
3152}
3153
chaviw98318de2021-05-19 16:45:23 -05003154bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003155 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003156 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3157 const WindowInfo* windowInfo = windowHandle->getInfo();
3158 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003159 if (windowHandle == otherHandle) {
3160 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003161 }
chaviw98318de2021-05-19 16:45:23 -05003162 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003163 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003164 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003165 return true;
3166 }
3167 }
3168 return false;
3169}
3170
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003171std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003172 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003173 if (applicationHandle != nullptr) {
3174 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003175 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 } else {
3177 return applicationHandle->getName();
3178 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003179 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003180 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003182 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184}
3185
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003186void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003187 if (!isUserActivityEvent(eventEntry)) {
3188 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003189 return;
3190 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003191
3192 const int32_t eventType = getUserActivityEventType(eventEntry);
3193 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3194 // Note that we're directly getting the time diff between the current event and the previous
3195 // event. This is assuming that the first user event always happens at a timestamp that is
3196 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3197 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3198 // value than the potential first user activity event time, so this is ok.
3199 std::chrono::nanoseconds timeSinceLastEvent =
3200 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3201 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3202 return;
3203 }
3204 }
3205
Tiger Huang721e26f2018-07-24 22:26:19 +08003206 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003207 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003208 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003209 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003210 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003211 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003212 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 }
3214 }
3215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003217 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003218 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3219 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 return;
3221 }
Josep del Riob3981622023-04-18 15:49:45 +00003222 if (windowDisablingUserActivityInfo != nullptr) {
3223 if (DEBUG_DISPATCH_CYCLE) {
3224 ALOGD("Not poking user activity: disabled by window '%s'.",
3225 windowDisablingUserActivityInfo->name.c_str());
3226 }
3227 return;
3228 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003231 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003232 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3233 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 return;
3235 }
Josep del Riob3981622023-04-18 15:49:45 +00003236 // If the key code is unknown, we don't consider it user activity
3237 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3238 return;
3239 }
3240 // Don't inhibit events that were intercepted or are not passed to
3241 // the apps, like system shortcuts
3242 if (windowDisablingUserActivityInfo != nullptr &&
3243 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3244 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3245 if (DEBUG_DISPATCH_CYCLE) {
3246 ALOGD("Not poking user activity: disabled by window '%s'.",
3247 windowDisablingUserActivityInfo->name.c_str());
3248 }
3249 return;
3250 }
3251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003254 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003255 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003256 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003257 break;
3258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
3260
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003261 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003262 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3263 REQUIRES(mLock) {
3264 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003265 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003266 };
3267 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268}
3269
3270void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003271 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003272 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003273 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003274 ATRACE_NAME_IF(ATRACE_ENABLED(),
3275 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3276 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003277 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003279 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003281 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003282 inputTarget.getPointerInfoString().c_str());
3283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
3285 // Skip this event if the connection status is not normal.
3286 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003287 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003288 if (DEBUG_DISPATCH_CYCLE) {
3289 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003290 connection->getInputChannelName().c_str(),
3291 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 return;
3294 }
3295
3296 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003298 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003299 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003300 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003302 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003303 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003304 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3305 logDispatchStateLocked();
3306 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3307 "target on connection "
3308 << connection->getInputChannelName() << " for "
3309 << originalMotionEntry.getDescription();
3310 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003312 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003313 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 if (!splitMotionEntry) {
3315 return; // split event was dropped
3316 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003317 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3318 std::string reason = std::string("reason=pointer cancel on split window");
3319 android_log_event_list(LOGTAG_INPUT_CANCEL)
3320 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3321 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003322 if (DEBUG_FOCUS) {
3323 ALOGD("channel '%s' ~ Split motion event.",
3324 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003325 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003326 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003327 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3328 std::move(splitMotionEntry),
3329 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 return;
3331 }
3332 }
3333
3334 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003335 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3336 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337}
3338
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3340 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3341 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003342 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003343 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3344 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003345 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003346
hongzuo liu95785e22022-09-06 02:51:35 +00003347 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003349 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
3351 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003352 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 startDispatchCycleLocked(currentTime, connection);
3354 }
3355}
3356
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003357void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003358 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003359 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003360 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3361 eventEntry->type == EventEntry::Type::MOTION;
3362 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3363 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3364 << inputTarget << " connection: " << connection->getInputChannelName()
3365 << " entry: " << eventEntry->getDescription();
3366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 // This is a new event.
3368 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003369 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003370 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3371 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003373 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3374 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003375 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003377 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003378 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003379 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3380 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003381 LOG(WARNING) << "channel " << connection->getInputChannelName()
3382 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 return; // skip the inconsistent event
3384 }
3385 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003388 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003389 std::shared_ptr<const MotionEntry> resolvedMotion =
3390 std::static_pointer_cast<const MotionEntry>(eventEntry);
3391 {
3392 // Determine the resolved motion entry.
3393 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3394 int32_t resolvedAction = motionEntry.action;
3395 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003397 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003398 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003399 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003400 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003401 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003402 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003403 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003404 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003405 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003406 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3407 }
3408 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3409 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3410 motionEntry.displayId)) {
3411 if (DEBUG_DISPATCH_CYCLE) {
3412 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3413 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3414 "enter event";
3415 }
3416 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3417 }
3418
3419 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3420 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3421 }
3422 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3423 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3424 }
3425 if (dispatchEntry->targetFlags.test(
3426 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3427 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3428 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003429 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3430 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3431 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003432
3433 dispatchEntry->resolvedFlags = resolvedFlags;
3434 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003435 std::optional<std::vector<PointerProperties>> usingProperties;
3436 std::optional<std::vector<PointerCoords>> usingCoords;
3437 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3438 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3439 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3440 // the dispatcher, and therefore the coordinates of this event are currently
3441 // incorrect. These events should use the coordinates of the last dispatched
3442 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3443 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3444 std::optional<std::pair<std::vector<PointerProperties>,
3445 std::vector<PointerCoords>>>
3446 pointerInfo =
3447 connection->inputState.getPointersOfLastEvent(motionEntry,
3448 hovering);
3449 if (pointerInfo) {
3450 usingProperties = pointerInfo->first;
3451 usingCoords = pointerInfo->second;
3452 }
3453 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003454 // Generate a new MotionEntry with a new eventId using the resolved action and
3455 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003456 resolvedMotion = std::make_shared<
3457 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3458 motionEntry.eventTime, motionEntry.deviceId,
3459 motionEntry.source, motionEntry.displayId,
3460 motionEntry.policyFlags, resolvedAction,
3461 motionEntry.actionButton, resolvedFlags,
3462 motionEntry.metaState, motionEntry.buttonState,
3463 motionEntry.classification, motionEntry.edgeFlags,
3464 motionEntry.xPrecision, motionEntry.yPrecision,
3465 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3466 motionEntry.downTime,
3467 usingProperties.value_or(motionEntry.pointerProperties),
3468 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003469 if (ATRACE_ENABLED()) {
3470 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3471 ") to MotionEvent(id=0x%" PRIx32 ").",
3472 motionEntry.id, resolvedMotion->id);
3473 ATRACE_NAME(message.c_str());
3474 }
3475
3476 // Set the resolved motion entry in the DispatchEntry.
3477 dispatchEntry->eventEntry = resolvedMotion;
3478 eventEntry = resolvedMotion;
3479 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003482 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3483 // devices being active at the same time in the same window, so if a new device is
3484 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003485 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003486 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003487 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003488 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003489 << connection->getInputChannelName() << " with event "
3490 << cancelEvent->getDescription();
3491 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003492 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003493 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003494
3495 // Send these cancel events to the queue before sending the event from the new
3496 // device.
3497 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3498 }
3499
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003500 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003501 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003502 LOG(WARNING) << "channel " << connection->getInputChannelName()
3503 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 return; // skip the inconsistent event
3505 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003506 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003507 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003508 // Skip reporting pointer down outside focus to the policy.
3509 break;
3510 }
3511
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003512 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003513 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514
3515 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003517 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003518 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3520 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003521 break;
3522 }
Chris Yef59a2f42020-10-16 12:55:26 -07003523 case EventEntry::Type::SENSOR: {
3524 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3525 break;
3526 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003527 case EventEntry::Type::CONFIGURATION_CHANGED:
3528 case EventEntry::Type::DEVICE_RESET: {
3529 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003530 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003531 break;
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534
3535 // Remember that we are waiting for this dispatch to complete.
3536 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003537 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539
3540 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003541 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003542 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003543}
3544
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003545/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003546 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003547 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003548 * The first role is to log input interaction with windows, which helps determine what the user was
3549 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3550 * that user started interacting with launcher window, as well as any other window that received
3551 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3552 * when the set of tokens that received the event changes. It is not logged again as long as the
3553 * user is interacting with the same windows.
3554 *
3555 * The second role is to track input device activity for metrics collection. For each input event,
3556 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3557 * input_interaction logs, the device interaction is reported even when the set of interaction
3558 * tokens do not change.
3559 *
3560 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3561 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003562 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003563void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3564 const std::vector<InputTarget>& targets) {
3565 int32_t deviceId;
3566 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003567 // Skip ACTION_UP events, and all events other than keys and motions
3568 if (entry.type == EventEntry::Type::KEY) {
3569 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3570 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3571 return;
3572 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003573 deviceId = keyEntry.deviceId;
3574 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003575 } else if (entry.type == EventEntry::Type::MOTION) {
3576 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3577 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003578 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3579 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 return;
3581 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003582 deviceId = motionEntry.deviceId;
3583 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003584 } else {
3585 return; // Not a key or a motion
3586 }
3587
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003588 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003589 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003590 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003591 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003592 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 continue; // Skip windows that receive ACTION_OUTSIDE
3594 }
3595
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003596 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003597 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003598 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003599 if (target.windowHandle) {
3600 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3601 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003602 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003603
3604 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3605 REQUIRES(mLock) {
3606 scoped_unlock unlock(mLock);
3607 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3608 };
3609 postCommandLocked(std::move(command));
3610
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003611 if (newConnectionTokens == mInteractionConnectionTokens) {
3612 return; // no change
3613 }
3614 mInteractionConnectionTokens = newConnectionTokens;
3615
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003616 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003617 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003618 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003619 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003620 std::string message = "Interaction with: " + targetList;
3621 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003622 message += "<none>";
3623 }
3624 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3625}
3626
chaviwfd6d3512019-03-25 13:23:49 -07003627void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003628 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003629 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003630 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3631 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003632 return;
3633 }
3634
Vishnu Nairc519ff72021-01-21 08:23:08 -08003635 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003636 if (focusedToken == token) {
3637 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003638 return;
3639 }
3640
Prabir Pradhancef936d2021-07-21 16:17:52 +00003641 auto command = [this, token]() REQUIRES(mLock) {
3642 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003643 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003644 };
3645 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646}
3647
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003648status_t InputDispatcher::publishMotionEvent(Connection& connection,
3649 DispatchEntry& dispatchEntry) const {
3650 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3651 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3652
3653 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003654 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003655
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003656 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003657 // Set the X and Y offset and X and Y scale depending on the input source.
3658 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003659 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003660 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3661 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003662 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003663 scaledCoords[i] = motionEntry.pointerCoords[i];
3664 // Don't apply window scale here since we don't want scale to affect raw
3665 // coordinates. The scale will be sent back to the client and applied
3666 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003667 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003668 }
3669 usingCoords = scaledCoords;
3670 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003671 }
3672
3673 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3674
3675 // Publish the motion event.
3676 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003677 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3678 motionEntry.source, motionEntry.displayId, std::move(hmac),
3679 motionEntry.action, motionEntry.actionButton,
3680 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3681 motionEntry.metaState, motionEntry.buttonState,
3682 motionEntry.classification, dispatchEntry.transform,
3683 motionEntry.xPrecision, motionEntry.yPrecision,
3684 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3685 dispatchEntry.rawTransform, motionEntry.downTime,
3686 motionEntry.eventTime, motionEntry.getPointerCount(),
3687 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003688}
3689
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003691 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003692 ATRACE_NAME_IF(ATRACE_ENABLED(),
3693 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3694 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003695 if (DEBUG_DISPATCH_CYCLE) {
3696 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003699 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003700 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003702 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003703 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
3705 // Publish the event.
3706 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003707 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3708 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003709 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003710 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3711 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003712 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003713 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3714 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003718 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003719 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3720 keyEntry.deviceId, keyEntry.source,
3721 keyEntry.displayId, std::move(hmac),
3722 keyEntry.action, dispatchEntry->resolvedFlags,
3723 keyEntry.keyCode, keyEntry.scanCode,
3724 keyEntry.metaState, keyEntry.repeatCount,
3725 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003726 if (mTracer) {
3727 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3728 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003729 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 }
3731
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003732 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003733 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003734 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3735 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003736 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003737 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003738 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003739 if (mTracer) {
3740 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3741 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003742 break;
3743 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003744
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003745 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003746 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003747 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003748 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003749 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003750 break;
3751 }
3752
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003753 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3754 const TouchModeEntry& touchModeEntry =
3755 static_cast<const TouchModeEntry&>(eventEntry);
3756 status = connection->inputPublisher
3757 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3758 touchModeEntry.inTouchMode);
3759
3760 break;
3761 }
3762
Prabir Pradhan99987712020-11-10 18:43:05 -08003763 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3764 const auto& captureEntry =
3765 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3766 status = connection->inputPublisher
3767 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003768 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003769 break;
3770 }
3771
arthurhungb89ccb02020-12-30 16:19:01 +08003772 case EventEntry::Type::DRAG: {
3773 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3774 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3775 dragEntry.id, dragEntry.x,
3776 dragEntry.y,
3777 dragEntry.isExiting);
3778 break;
3779 }
3780
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003781 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003782 case EventEntry::Type::DEVICE_RESET:
3783 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003784 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003785 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
3789
3790 // Check the result.
3791 if (status) {
3792 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003793 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003795 "This is unexpected because the wait queue is empty, so the pipe "
3796 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003797 "event to it, status=%s(%d)",
3798 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3799 status);
Harry Cutts33476232023-01-30 19:57:29 +00003800 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 } else {
3802 // Pipe is full and we are waiting for the app to finish process some events
3803 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003804 if (DEBUG_DISPATCH_CYCLE) {
3805 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3806 "waiting for the application to catch up",
3807 connection->getInputChannelName().c_str());
3808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 }
3810 } else {
3811 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003812 "status=%s(%d)",
3813 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3814 status);
Harry Cutts33476232023-01-30 19:57:29 +00003815 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817 return;
3818 }
3819
3820 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003821 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3822 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3823 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003824 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003825 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003826 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003827 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003828 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 }
3830}
3831
chaviw09c8d2d2020-08-24 15:48:26 -07003832std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3833 size_t size;
3834 switch (event.type) {
3835 case VerifiedInputEvent::Type::KEY: {
3836 size = sizeof(VerifiedKeyEvent);
3837 break;
3838 }
3839 case VerifiedInputEvent::Type::MOTION: {
3840 size = sizeof(VerifiedMotionEvent);
3841 break;
3842 }
3843 }
3844 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3845 return mHmacKeyManager.sign(start, size);
3846}
3847
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003848const std::array<uint8_t, 32> InputDispatcher::getSignature(
3849 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003850 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003851 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003852 // Only sign events up and down events as the purely move events
3853 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003854 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003855 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003856
3857 VerifiedMotionEvent verifiedEvent =
3858 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3859 verifiedEvent.actionMasked = actionMasked;
3860 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3861 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003862}
3863
3864const std::array<uint8_t, 32> InputDispatcher::getSignature(
3865 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3866 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3867 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003868 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003869}
3870
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003872 const std::shared_ptr<Connection>& connection,
3873 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003874 if (DEBUG_DISPATCH_CYCLE) {
3875 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3876 connection->getInputChannelName().c_str(), seq, toString(handled));
3877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003879 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 return;
3881 }
3882
3883 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003884 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3885 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3886 };
3887 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888}
3889
3890void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003891 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003893 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003894 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3895 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
3898 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003899 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003900 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003901 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003902 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
3904 // The connection appears to be unrecoverably broken.
3905 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003906 if (connection->status == Connection::Status::NORMAL) {
3907 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
3909 if (notify) {
3910 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003911 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3912 connection->getInputChannelName().c_str());
3913
3914 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003915 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003916 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003917 };
3918 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 }
3920 }
3921}
3922
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003923void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003924 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003925 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003926 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 }
3928}
3929
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003930void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003932 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934}
3935
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003936int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3937 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003938 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003939 if (connection == nullptr) {
3940 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3941 connectionToken.get(), events);
3942 return 0; // remove the callback
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003945 bool notify;
3946 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3947 if (!(events & ALOOPER_EVENT_INPUT)) {
3948 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3949 "events=0x%x",
3950 connection->getInputChannelName().c_str(), events);
3951 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 }
3953
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003954 nsecs_t currentTime = now();
3955 bool gotOne = false;
3956 status_t status = OK;
3957 for (;;) {
3958 Result<InputPublisher::ConsumerResponse> result =
3959 connection->inputPublisher.receiveConsumerResponse();
3960 if (!result.ok()) {
3961 status = result.error().code();
3962 break;
3963 }
3964
3965 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3966 const InputPublisher::Finished& finish =
3967 std::get<InputPublisher::Finished>(*result);
3968 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3969 finish.consumeTime);
3970 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003971 if (shouldReportMetricsForConnection(*connection)) {
3972 const InputPublisher::Timeline& timeline =
3973 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003974 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3975 connection->getToken(),
3976 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003977 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003978 }
3979 gotOne = true;
3980 }
3981 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003982 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003983 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 return 1;
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003988 notify = status != DEAD_OBJECT || !connection->monitor;
3989 if (notify) {
3990 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3991 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3992 status);
3993 }
3994 } else {
3995 // Monitor channels are never explicitly unregistered.
3996 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003997 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003998 notify = !connection->monitor && stillHaveWindowHandle;
3999 if (notify) {
4000 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4001 connection->getInputChannelName().c_str(), events);
4002 }
4003 }
4004
4005 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004006 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004007 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008}
4009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004012 // Cancel windows (i.e. non-monitors).
4013 // A channel must have at least one window to receive any input. If a window was removed, the
4014 // event streams directed to the window will already have been canceled during window removal.
4015 // So there is no need to generate cancellations for connections without any windows.
4016 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4017 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4018 // through a non-touched window if there are more than one window for an input channel.
4019 if (cancelPointers) {
4020 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4021 if (options.displayId.has_value() && options.displayId != displayId) {
4022 continue;
4023 }
4024 for (const auto& touchedWindow : touchState.windows) {
4025 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4026 }
4027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004029 // Follow up by generating cancellations for all windows, because we don't explicitly track
4030 // the windows that have an ongoing focus event stream.
4031 if (cancelNonPointers) {
4032 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4033 for (const auto& windowHandle : handles) {
4034 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4035 }
4036 }
4037 }
4038
4039 // Cancel monitors.
4040 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041}
4042
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004044 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004045 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004046 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004047 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4048 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004049 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004050 }
4051}
4052
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004053void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4054 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4055 const std::shared_ptr<Connection>& connection) {
4056 if (windowHandle == nullptr) {
4057 LOG(FATAL) << __func__ << ": Window handle must not be null";
4058 }
4059 if (connection) {
4060 // The connection can be optionally provided to avoid multiple lookups.
4061 if (windowHandle->getToken() != connection->getToken()) {
4062 LOG(FATAL) << __func__
4063 << ": Wrong connection provided for window: " << windowHandle->getName();
4064 }
4065 }
4066
4067 std::shared_ptr<Connection> resolvedConnection =
4068 connection ? connection : getConnectionLocked(windowHandle->getToken());
4069 if (!resolvedConnection) {
4070 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4071 return;
4072 }
4073 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4074}
4075
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004077 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4078 const sp<WindowInfoHandle>& window) {
4079 if (!connection->monitor && window == nullptr) {
4080 LOG(FATAL) << __func__
4081 << ": Cannot send event to non-monitor channel without a window - channel: "
4082 << connection->getInputChannelName();
4083 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004084 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 return;
4086 }
4087
4088 nsecs_t currentTime = now();
4089
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004090 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004091 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004093 if (cancelationEvents.empty()) {
4094 return;
4095 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004096
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4098 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004099 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004100 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004101 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004102 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004103
Arthur Hungb3307ee2021-10-14 10:57:37 +00004104 std::string reason = std::string("reason=").append(options.reason);
4105 android_log_event_list(LOGTAG_INPUT_CANCEL)
4106 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4107
hongzuo liu95785e22022-09-06 02:51:35 +00004108 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004109 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004110 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004111 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004112
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004113 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004114 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004115 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004116
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004117 switch (cancelationEventEntry->type) {
4118 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004119 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004120 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004121 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4122 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004123 } else {
4124 targets.emplace_back(fallbackTarget);
4125 }
4126 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004127 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004129 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004130 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004131 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004132 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004133 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004134 pointerIndex++) {
4135 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4136 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004137 if (mDragState && mDragState->dragWindow->getToken() == token &&
4138 pointerIds.test(mDragState->pointerId)) {
4139 LOG(INFO) << __func__
4140 << ": Canceling drag and drop because the pointers for the drag "
4141 "window are being canceled.";
4142 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4143 mDragState.reset();
4144 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004145 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4146 ftl::Flags<InputTarget::Flags>(), pointerIds,
4147 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004148 } else {
4149 targets.emplace_back(fallbackTarget);
4150 const auto it = mDisplayInfos.find(motionEntry.displayId);
4151 if (it != mDisplayInfos.end()) {
4152 targets.back().displayTransform = it->second.transform;
4153 targets.back().setDefaultPointerTransform(it->second.transform);
4154 }
4155 }
4156 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004157 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004159 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004160 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004161 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4162 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004163 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004164 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004165 break;
4166 }
4167 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004168 case EventEntry::Type::DEVICE_RESET:
4169 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004170 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004171 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004172 break;
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004176 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004177 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004179
hongzuo liu95785e22022-09-06 02:51:35 +00004180 // If the outbound queue was previously empty, start the dispatch cycle going.
4181 if (wasEmpty && !connection->outboundQueue.empty()) {
4182 startDispatchCycleLocked(currentTime, connection);
4183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184}
4185
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004187 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004188 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004189 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190 return;
4191 }
4192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004193 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004194 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195
4196 if (downEvents.empty()) {
4197 return;
4198 }
4199
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004200 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4202 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004204
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004205 const auto [_, touchedWindowState, displayId] =
4206 findTouchStateWindowAndDisplayLocked(connection->getToken());
4207 if (touchedWindowState == nullptr) {
4208 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4209 }
4210 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211
hongzuo liu95785e22022-09-06 02:51:35 +00004212 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004213 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004214 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004215 switch (downEventEntry->type) {
4216 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004217 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4218 if (windowHandle != nullptr) {
4219 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004220 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004221 pointerIndex++) {
4222 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4223 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004224 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4225 targetFlags, pointerIds, motionEntry.downTime,
4226 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004227 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004228 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004229 const auto it = mDisplayInfos.find(motionEntry.displayId);
4230 if (it != mDisplayInfos.end()) {
4231 targets.back().displayTransform = it->second.transform;
4232 targets.back().setDefaultPointerTransform(it->second.transform);
4233 }
4234 }
4235 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004236 break;
4237 }
4238
4239 case EventEntry::Type::KEY:
4240 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004241 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004242 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004243 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004244 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004245 case EventEntry::Type::SENSOR:
4246 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004247 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004248 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004249 break;
4250 }
4251 }
4252
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004253 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004254 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004255 }
4256
hongzuo liu95785e22022-09-06 02:51:35 +00004257 // If the outbound queue was previously empty, start the dispatch cycle going.
4258 if (wasEmpty && !connection->outboundQueue.empty()) {
4259 startDispatchCycleLocked(downTime, connection);
4260 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004261}
4262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004264 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4265 nsecs_t splitDownTime) {
4266 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
4268 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004269 std::vector<PointerProperties> splitPointerProperties;
4270 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004272 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 uint32_t splitPointerCount = 0;
4274
4275 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004278 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004280 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004282 splitPointerProperties.push_back(pointerProperties);
4283 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 splitPointerCount += 1;
4285 }
4286 }
4287
4288 if (splitPointerCount != pointerIds.count()) {
4289 // This is bad. We are missing some of the pointers that we expected to deliver.
4290 // Most likely this indicates that we received an ACTION_MOVE events that has
4291 // different pointer ids than we expected based on the previous ACTION_DOWN
4292 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4293 // in this way.
4294 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004295 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004296 "a broken sequence of pointer ids from the input device: %s",
4297 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004298 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
4300
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004301 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4304 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004305 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004307 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004309 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 if (pointerIds.count() == 1) {
4311 // The first/last pointer went down/up.
4312 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004313 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004314 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4315 ? AMOTION_EVENT_ACTION_CANCEL
4316 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 } else {
4318 // A secondary pointer went down/up.
4319 uint32_t splitPointerIndex = 0;
4320 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4321 splitPointerIndex += 1;
4322 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004323 action = maskedAction |
4324 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 }
4326 } else {
4327 // An unrelated pointer changed.
4328 action = AMOTION_EVENT_ACTION_MOVE;
4329 }
4330 }
4331
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004332 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4333 logDispatchStateLocked();
4334 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4335 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4336 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004337 }
4338
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004339 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004340 ATRACE_NAME_IF(ATRACE_ENABLED(),
4341 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4342 ").",
4343 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004344 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004345 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4346 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004347 originalMotionEntry.deviceId, originalMotionEntry.source,
4348 originalMotionEntry.displayId,
4349 originalMotionEntry.policyFlags, action,
4350 originalMotionEntry.actionButton,
4351 originalMotionEntry.flags, originalMotionEntry.metaState,
4352 originalMotionEntry.buttonState,
4353 originalMotionEntry.classification,
4354 originalMotionEntry.edgeFlags,
4355 originalMotionEntry.xPrecision,
4356 originalMotionEntry.yPrecision,
4357 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004358 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004359 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 return splitMotionEntry;
4362}
4363
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004364void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4365 std::scoped_lock _l(mLock);
4366 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4367}
4368
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004369void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004370 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004371 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Antonio Kantekf16f2832021-09-28 04:39:20 +00004374 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004378 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004380 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 } // release lock
4382
4383 if (needWake) {
4384 mLooper->wake();
4385 }
4386}
4387
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004388void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004389 ALOGD_IF(debugInboundEventDetails(),
4390 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4391 ", deviceId=%d, source=%s, displayId=%" PRId32
4392 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4393 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004394 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4395 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4396 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004397 Result<void> keyCheck = validateKeyEvent(args.action);
4398 if (!keyCheck.ok()) {
4399 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 return;
4401 }
4402
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004403 uint32_t policyFlags = args.policyFlags;
4404 int32_t flags = args.flags;
4405 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004406 // InputDispatcher tracks and generates key repeats on behalf of
4407 // whatever notifies it, so repeatCount should always be set to 0
4408 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4410 policyFlags |= POLICY_FLAG_VIRTUAL;
4411 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 if (policyFlags & POLICY_FLAG_FUNCTION) {
4414 metaState |= AMETA_FUNCTION_ON;
4415 }
4416
4417 policyFlags |= POLICY_FLAG_TRUSTED;
4418
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004419 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004421 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4422 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4423 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
Michael Wright2b3c3302018-03-02 17:19:13 +00004425 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004426 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004427 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4428 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Antonio Kantekf16f2832021-09-28 04:39:20 +00004432 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 { // acquire lock
4434 mLock.lock();
4435
4436 if (shouldSendKeyToInputFilterLocked(args)) {
4437 mLock.unlock();
4438
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004439 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004440 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 return; // event was consumed by the filter
4442 }
4443
4444 mLock.lock();
4445 }
4446
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004448 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4449 args.deviceId, args.source, args.displayId, policyFlags,
4450 args.action, flags, keyCode, args.scanCode, metaState,
4451 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004452 if (mTracer) {
4453 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004456 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 mLock.unlock();
4458 } // release lock
4459
4460 if (needWake) {
4461 mLooper->wake();
4462 }
4463}
4464
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 return mInputFilterEnabled;
4467}
4468
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004469void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004470 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004471 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004473 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4475 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004476 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4477 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4478 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4479 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4480 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004481 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004482 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4483 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004484 i, args.pointerProperties[i].id,
4485 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4486 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4487 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4488 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4489 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4490 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4491 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4492 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4493 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4494 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004497
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004498 Result<void> motionCheck =
4499 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4500 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004501 if (!motionCheck.ok()) {
4502 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4503 return;
4504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004506 if (DEBUG_VERIFY_EVENTS) {
4507 auto [it, _] =
4508 mVerifiersByDisplay.try_emplace(args.displayId,
4509 StringPrintf("display %" PRId32, args.displayId));
4510 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004511 it->second.processMovement(args.deviceId, args.source, args.action,
4512 args.getPointerCount(), args.pointerProperties.data(),
4513 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004514 if (!result.ok()) {
4515 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4516 }
4517 }
4518
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004519 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004521
4522 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004523 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4524 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004525 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4526 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529
Antonio Kantekf16f2832021-09-28 04:39:20 +00004530 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 { // acquire lock
4532 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004533 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4534 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4535 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004536 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004537 if (touchStateIt != mTouchStatesByDisplay.end()) {
4538 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004539 if (touchState.hasTouchingPointers(args.deviceId) ||
4540 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004541 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4542 }
4543 }
4544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545
4546 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004547 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004548 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004549 displayTransform = it->second.transform;
4550 }
4551
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 mLock.unlock();
4553
4554 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004555 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4556 args.action, args.actionButton, args.flags, args.edgeFlags,
4557 args.metaState, args.buttonState, args.classification,
4558 displayTransform, args.xPrecision, args.yPrecision,
4559 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004560 args.downTime, args.eventTime, args.getPointerCount(),
4561 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562
4563 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004564 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 return; // event was consumed by the filter
4566 }
4567
4568 mLock.lock();
4569 }
4570
4571 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004572 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004573 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4574 args.deviceId, args.source, args.displayId,
4575 policyFlags, args.action, args.actionButton,
4576 args.flags, args.metaState, args.buttonState,
4577 args.classification, args.edgeFlags, args.xPrecision,
4578 args.yPrecision, args.xCursorPosition,
4579 args.yCursorPosition, args.downTime,
4580 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004581 if (mTracer) {
4582 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004585 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4586 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004587 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004588 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004589 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4590 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4591 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004592 }
4593
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004594 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 mLock.unlock();
4596 } // release lock
4597
4598 if (needWake) {
4599 mLooper->wake();
4600 }
4601}
4602
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004603void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004604 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004605 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4606 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004607 args.id, args.eventTime, args.deviceId, args.source,
4608 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004609 }
Chris Yef59a2f42020-10-16 12:55:26 -07004610
Antonio Kantekf16f2832021-09-28 04:39:20 +00004611 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004612 { // acquire lock
4613 mLock.lock();
4614
4615 // Just enqueue a new sensor event.
4616 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004617 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4618 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4619 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004620
4621 needWake = enqueueInboundEventLocked(std::move(newEntry));
4622 mLock.unlock();
4623 } // release lock
4624
4625 if (needWake) {
4626 mLooper->wake();
4627 }
4628}
4629
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004630void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004631 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004632 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4633 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004634 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004635 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004636}
4637
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004638bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004639 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640}
4641
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004642void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004643 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004644 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4645 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004649 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004651 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652}
4653
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004654void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004655 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4657 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659
Antonio Kantekf16f2832021-09-28 04:39:20 +00004660 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004662 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004664 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004665 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004666 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004667
4668 for (auto& [_, verifier] : mVerifiersByDisplay) {
4669 verifier.resetDevice(args.deviceId);
4670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 } // release lock
4672
4673 if (needWake) {
4674 mLooper->wake();
4675 }
4676}
4677
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004678void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004679 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004680 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4681 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004682 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004683
Antonio Kantekf16f2832021-09-28 04:39:20 +00004684 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004685 { // acquire lock
4686 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004687 auto entry =
4688 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004689 needWake = enqueueInboundEventLocked(std::move(entry));
4690 } // release lock
4691
4692 if (needWake) {
4693 mLooper->wake();
4694 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004695}
4696
Prabir Pradhan5735a322022-04-11 17:23:34 +00004697InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004698 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004699 InputEventInjectionSync syncMode,
4700 std::chrono::milliseconds timeout,
4701 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004702 Result<void> eventValidation = validateInputEvent(*event);
4703 if (!eventValidation.ok()) {
4704 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4705 return InputEventInjectionResult::FAILED;
4706 }
4707
Prabir Pradhan65613802023-02-22 23:36:58 +00004708 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004709 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4710 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4711 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4712 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004713 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004714 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
Prabir Pradhan5735a322022-04-11 17:23:34 +00004716 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004718 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004719 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4720 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4721 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4722 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4723 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004724 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004725 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004726 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004727 }
4728
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004729 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4730 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4731
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004732 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004734 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004735 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004736 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004737 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004738 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4739 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4740 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004741 int32_t keyCode = incomingKey.getKeyCode();
4742 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004743 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004744 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004745 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4746 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4747 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004749 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4750 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004751 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752
4753 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4754 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004755 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4757 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4758 std::to_string(t.duration().count()).c_str());
4759 }
4760 }
4761
4762 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004763 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004764 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4765 incomingKey.getEventTime(), resolvedDeviceId,
4766 incomingKey.getSource(), incomingKey.getDisplayId(),
4767 policyFlags, action, flags, keyCode,
4768 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004769 incomingKey.getRepeatCount(),
4770 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004771 if (mTracer) {
4772 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4773 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004774 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 }
4777
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004778 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004779 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004780 const bool isPointerEvent =
4781 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4782 // If a pointer event has no displayId specified, inject it to the default display.
4783 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4784 ? ADISPLAY_ID_DEFAULT
4785 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004786 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787
4788 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004789 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004790 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004791 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4792 motionEvent.getAction(), eventTime,
4793 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4795 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4796 std::to_string(t.duration().count()).c_str());
4797 }
4798 }
4799
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004800 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4801 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4802 }
4803
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004805 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004806 const size_t pointerCount = motionEvent.getPointerCount();
4807 const std::vector<PointerProperties>
4808 pointerProperties(motionEvent.getPointerProperties(),
4809 motionEvent.getPointerProperties() + pointerCount);
4810
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004811 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004812 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004813 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4814 *sampleEventTimes, resolvedDeviceId,
4815 motionEvent.getSource(), displayId, policyFlags,
4816 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004817 motionEvent.getActionButton(), flags,
4818 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004819 motionEvent.getButtonState(),
4820 motionEvent.getClassification(),
4821 motionEvent.getEdgeFlags(),
4822 motionEvent.getXPrecision(),
4823 motionEvent.getYPrecision(),
4824 motionEvent.getRawXCursorPosition(),
4825 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004826 motionEvent.getDownTime(), pointerProperties,
4827 std::vector<PointerCoords>(samplePointerCoords,
4828 samplePointerCoords +
4829 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004830 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004831 if (mTracer) {
4832 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4833 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004834 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004835 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004836 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004837 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004838 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004839 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4840 resolvedDeviceId, motionEvent.getSource(), displayId,
4841 policyFlags, motionEvent.getAction(),
4842 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004843 motionEvent.getMetaState(), motionEvent.getButtonState(),
4844 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4845 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4846 motionEvent.getRawXCursorPosition(),
4847 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4848 pointerProperties,
4849 std::vector<PointerCoords>(samplePointerCoords,
4850 samplePointerCoords +
4851 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004852 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4853 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004854 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 }
4856 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004859 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004860 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004861 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004865 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004866 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004867 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004868 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004869 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004870 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872
4873 mLock.unlock();
4874
4875 if (needWake) {
4876 mLooper->wake();
4877 }
4878
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004879 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004881 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 if (syncMode == InputEventInjectionSync::NONE) {
4884 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 } else {
4886 for (;;) {
4887 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004888 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 break;
4890 }
4891
4892 nsecs_t remainingTimeout = endTime - now();
4893 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004894 if (DEBUG_INJECTION) {
4895 ALOGD("injectInputEvent - Timed out waiting for injection result "
4896 "to become available.");
4897 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 break;
4900 }
4901
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004902 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 }
4904
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004905 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4906 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004908 if (DEBUG_INJECTION) {
4909 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4910 injectionState->pendingForegroundDispatches);
4911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 nsecs_t remainingTimeout = endTime - now();
4913 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004914 if (DEBUG_INJECTION) {
4915 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4916 "dispatches to finish.");
4917 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004918 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 break;
4920 }
4921
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004922 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 }
4924 }
4925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 } // release lock
4927
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004928 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004929 LOG(INFO) << "injectInputEvent - Finished with result "
4930 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
4933 return injectionResult;
4934}
4935
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004936std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004937 std::array<uint8_t, 32> calculatedHmac;
4938 std::unique_ptr<VerifiedInputEvent> result;
4939 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004940 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004941 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4942 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4943 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004944 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004945 break;
4946 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004947 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004948 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4949 VerifiedMotionEvent verifiedMotionEvent =
4950 verifiedMotionEventFromMotionEvent(motionEvent);
4951 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004952 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004953 break;
4954 }
4955 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004956 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004957 return nullptr;
4958 }
4959 }
4960 if (calculatedHmac == INVALID_HMAC) {
4961 return nullptr;
4962 }
tyiu1573a672023-02-21 22:38:32 +00004963 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004964 return nullptr;
4965 }
4966 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004967}
4968
Prabir Pradhan24047542023-11-02 17:14:59 +00004969void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004970 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004971 if (!entry.injectionState) {
4972 // Not an injected event.
4973 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004975
4976 InjectionState& injectionState = *entry.injectionState;
4977 if (DEBUG_INJECTION) {
4978 LOG(INFO) << "Setting input event injection result to "
4979 << ftl::enum_string(injectionResult);
4980 }
4981
4982 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4983 // Log the outcome since the injector did not wait for the injection result.
4984 switch (injectionResult) {
4985 case InputEventInjectionResult::SUCCEEDED:
4986 ALOGV("Asynchronous input event injection succeeded.");
4987 break;
4988 case InputEventInjectionResult::TARGET_MISMATCH:
4989 ALOGV("Asynchronous input event injection target mismatch.");
4990 break;
4991 case InputEventInjectionResult::FAILED:
4992 ALOGW("Asynchronous input event injection failed.");
4993 break;
4994 case InputEventInjectionResult::TIMED_OUT:
4995 ALOGW("Asynchronous input event injection timed out.");
4996 break;
4997 case InputEventInjectionResult::PENDING:
4998 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4999 break;
5000 }
5001 }
5002
5003 injectionState.injectionResult = injectionResult;
5004 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005}
5006
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005007void InputDispatcher::transformMotionEntryForInjectionLocked(
5008 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005009 // Input injection works in the logical display coordinate space, but the input pipeline works
5010 // display space, so we need to transform the injected events accordingly.
5011 const auto it = mDisplayInfos.find(entry.displayId);
5012 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005013 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005014
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005015 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5016 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5017 const vec2 cursor =
5018 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5019 {entry.xCursorPosition, entry.yCursorPosition});
5020 entry.xCursorPosition = cursor.x;
5021 entry.yCursorPosition = cursor.y;
5022 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005023 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005024 entry.pointerCoords[i] =
5025 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5026 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005027 }
5028}
5029
Prabir Pradhan24047542023-11-02 17:14:59 +00005030void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005031 if (entry.injectionState) {
5032 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 }
5034}
5035
Prabir Pradhan24047542023-11-02 17:14:59 +00005036void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005037 if (entry.injectionState) {
5038 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005040 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005041 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 }
5043 }
5044}
5045
chaviw98318de2021-05-19 16:45:23 -05005046const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005047 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005048 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005049 auto it = mWindowHandlesByDisplay.find(displayId);
5050 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005051}
5052
chaviw98318de2021-05-19 16:45:23 -05005053sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005054 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005055 if (windowHandleToken == nullptr) {
5056 return nullptr;
5057 }
5058
Prabir Pradhan16463382023-10-12 23:03:19 +00005059 if (!displayId) {
5060 // Look through all displays.
5061 for (auto& it : mWindowHandlesByDisplay) {
5062 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5063 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5064 if (windowHandle->getToken() == windowHandleToken) {
5065 return windowHandle;
5066 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005069 return nullptr;
5070 }
5071
Prabir Pradhan16463382023-10-12 23:03:19 +00005072 // Only look through the requested display.
5073 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005074 if (windowHandle->getToken() == windowHandleToken) {
5075 return windowHandle;
5076 }
5077 }
5078 return nullptr;
5079}
5080
chaviw98318de2021-05-19 16:45:23 -05005081sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5082 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005083 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005084 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5085 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005086 if (handle->getId() == windowHandle->getId() &&
5087 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005088 if (windowHandle->getInfo()->displayId != it.first) {
5089 ALOGE("Found window %s in display %" PRId32
5090 ", but it should belong to display %" PRId32,
5091 windowHandle->getName().c_str(), it.first,
5092 windowHandle->getInfo()->displayId);
5093 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005094 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 }
5097 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005098 return nullptr;
5099}
5100
chaviw98318de2021-05-19 16:45:23 -05005101sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005102 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5103 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104}
5105
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005106ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5107 auto displayInfoIt = mDisplayInfos.find(displayId);
5108 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5109 : kIdentityTransform;
5110}
5111
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005112bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5113 const MotionEntry& motionEntry) const {
5114 const WindowInfo& info = *window->getInfo();
5115
5116 // Skip spy window targets that are not valid for targeted injection.
5117 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005118 return false;
5119 }
5120
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005121 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5122 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5123 return false;
5124 }
5125
5126 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5127 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5128 window->getName().c_str());
5129 return false;
5130 }
5131
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005132 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005133 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005134 ALOGW("Not sending touch to %s because there's no corresponding connection",
5135 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005136 return false;
5137 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005138
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005139 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005140 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 return false;
5142 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005143
5144 // Drop events that can't be trusted due to occlusion
5145 const auto [x, y] = resolveTouchedPosition(motionEntry);
5146 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5147 if (!isTouchTrustedLocked(occlusionInfo)) {
5148 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005149 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005150 for (const auto& log : occlusionInfo.debugInfo) {
5151 ALOGD("%s", log.c_str());
5152 }
5153 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005154 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5155 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005156 return false;
5157 }
5158
5159 // Drop touch events if requested by input feature
5160 if (shouldDropInput(motionEntry, window)) {
5161 return false;
5162 }
5163
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005164 // Ignore touches if stylus is down anywhere on screen
5165 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5166 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5167 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5168 return false;
5169 }
5170
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005171 return true;
5172}
5173
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005174void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005175 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5176 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005177 // Remove all handles on a display if there are no windows left.
5178 mWindowHandlesByDisplay.erase(displayId);
5179 return;
5180 }
5181
5182 // Since we compare the pointer of input window handles across window updates, we need
5183 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005184 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5185 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5186 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005187 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005188 }
5189
chaviw98318de2021-05-19 16:45:23 -05005190 std::vector<sp<WindowInfoHandle>> newHandles;
5191 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005192 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005193 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005194 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005195 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005196 const bool canReceiveInput =
5197 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5198 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005199 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005200 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005201 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005202 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005203 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005204 }
5205
5206 if (info->displayId != displayId) {
5207 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5208 handle->getName().c_str(), displayId, info->displayId);
5209 continue;
5210 }
5211
Robert Carredd13602020-04-13 17:24:34 -07005212 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5213 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005214 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005215 oldHandle->updateFrom(handle);
5216 newHandles.push_back(oldHandle);
5217 } else {
5218 newHandles.push_back(handle);
5219 }
5220 }
5221
5222 // Insert or replace
5223 mWindowHandlesByDisplay[displayId] = newHandles;
5224}
5225
Arthur Hungb92218b2018-08-14 12:00:21 +08005226/**
5227 * Called from InputManagerService, update window handle list by displayId that can receive input.
5228 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5229 * If set an empty list, remove all handles from the specific display.
5230 * For focused handle, check if need to change and send a cancel event to previous one.
5231 * For removed handle, check if need to send a cancel event if already in touch.
5232 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005233void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005234 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005235 if (DEBUG_FOCUS) {
5236 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005237 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005238 windowList += iwh->getName() + " ";
5239 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005240 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242
Prabir Pradhand65552b2021-10-07 11:23:50 -07005243 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005244 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005245 const WindowInfo& info = *window->getInfo();
5246
5247 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005248 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005249 if (noInputWindow && window->getToken() != nullptr) {
5250 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5251 window->getName().c_str());
5252 window->releaseChannel();
5253 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005254
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005255 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005256 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5257 !info.inputConfig.test(
5258 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005259 "%s has feature SPY, but is not a trusted overlay.",
5260 window->getName().c_str());
5261
Prabir Pradhand65552b2021-10-07 11:23:50 -07005262 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005263 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5264 !info.inputConfig.test(
5265 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005266 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5267 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005268 }
5269
Arthur Hung72d8dc32020-03-28 00:48:39 +00005270 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005271 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005272 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273
chaviw98318de2021-05-19 16:45:23 -05005274 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005275
chaviw98318de2021-05-19 16:45:23 -05005276 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005277
Vishnu Nairc519ff72021-01-21 08:23:08 -08005278 std::optional<FocusResolver::FocusChanges> changes =
5279 mFocusResolver.setInputWindows(displayId, windowHandles);
5280 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005281 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005284 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5285 mTouchStatesByDisplay.find(displayId);
5286 if (stateIt != mTouchStatesByDisplay.end()) {
5287 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005288 for (size_t i = 0; i < state.windows.size();) {
5289 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005290 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005291 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5292 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005293 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5294 "touched window was removed");
5295 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5296 // Since we are about to drop the touch, cancel the events for the wallpaper as
5297 // well.
5298 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5299 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5300 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5301 if (const auto& ww = state.getWallpaperWindow(); ww) {
5302 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005305 state.windows.erase(state.windows.begin() + i);
5306 } else {
5307 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 }
5309 }
arthurhungb89ccb02020-12-30 16:19:01 +08005310
arthurhung6d4bed92021-03-17 11:59:33 +08005311 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005312 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005313 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005314 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005315 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005316 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5317 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005318 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005319 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005320 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005321
Arthur Hung72d8dc32020-03-28 00:48:39 +00005322 // Release information for windows that are no longer present.
5323 // This ensures that unused input channels are released promptly.
5324 // Otherwise, they might stick around until the window handle is destroyed
5325 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005326 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005327 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005328 if (DEBUG_FOCUS) {
5329 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005330 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005331 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005332 }
chaviw291d88a2019-02-14 10:33:58 -08005333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334}
5335
5336void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005337 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005338 if (DEBUG_FOCUS) {
5339 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5340 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5341 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005342 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005343 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005344 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 } // release lock
5346
5347 // Wake up poll loop since it may need to make new input dispatching choices.
5348 mLooper->wake();
5349}
5350
Vishnu Nair599f1412021-06-21 10:39:58 -07005351void InputDispatcher::setFocusedApplicationLocked(
5352 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5353 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5354 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5355
5356 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5357 return; // This application is already focused. No need to wake up or change anything.
5358 }
5359
5360 // Set the new application handle.
5361 if (inputApplicationHandle != nullptr) {
5362 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5363 } else {
5364 mFocusedApplicationHandlesByDisplay.erase(displayId);
5365 }
5366
5367 // No matter what the old focused application was, stop waiting on it because it is
5368 // no longer focused.
5369 resetNoFocusedWindowTimeoutLocked();
5370}
5371
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005372void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5373 if (interval.count() < 0) {
5374 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5375 }
5376 std::scoped_lock _l(mLock);
5377 mMinTimeBetweenUserActivityPokes = interval;
5378}
5379
Tiger Huang721e26f2018-07-24 22:26:19 +08005380/**
5381 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5382 * the display not specified.
5383 *
5384 * We track any unreleased events for each window. If a window loses the ability to receive the
5385 * released event, we will send a cancel event to it. So when the focused display is changed, we
5386 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5387 * display. The display-specified events won't be affected.
5388 */
5389void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005390 if (DEBUG_FOCUS) {
5391 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5392 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005393 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005394 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005395
5396 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005397 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005398 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005399 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005400 const auto windowHandle =
5401 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5402 if (windowHandle == nullptr) {
5403 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005404 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005405 CancelationOptions
5406 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5407 "The display which contains this window no longer has focus.");
5408 options.displayId = ADISPLAY_ID_NONE;
5409 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005410 }
5411 mFocusedDisplayId = displayId;
5412
Chris Ye3c2d6f52020-08-09 10:39:48 -07005413 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005414 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005415 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005416
Vishnu Nairad321cd2020-08-20 16:40:21 -07005417 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005418 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005419 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005420 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005421 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005422 }
5423 }
5424 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005425 } // release lock
5426
5427 // Wake up poll loop since it may need to make new input dispatching choices.
5428 mLooper->wake();
5429}
5430
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005432 if (DEBUG_FOCUS) {
5433 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
5436 bool changed;
5437 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005438 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439
5440 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5441 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005442 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443 }
5444
5445 if (mDispatchEnabled && !enabled) {
5446 resetAndDropEverythingLocked("dispatcher is being disabled");
5447 }
5448
5449 mDispatchEnabled = enabled;
5450 mDispatchFrozen = frozen;
5451 changed = true;
5452 } else {
5453 changed = false;
5454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 } // release lock
5456
5457 if (changed) {
5458 // Wake up poll loop since it may need to make new input dispatching choices.
5459 mLooper->wake();
5460 }
5461}
5462
5463void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005464 if (DEBUG_FOCUS) {
5465 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467
5468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470
5471 if (mInputFilterEnabled == enabled) {
5472 return;
5473 }
5474
5475 mInputFilterEnabled = enabled;
5476 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5477 } // release lock
5478
5479 // Wake up poll loop since there might be work to do to drop everything.
5480 mLooper->wake();
5481}
5482
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005483bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005484 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005485 bool needWake = false;
5486 {
5487 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005488 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005489 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005490 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005491 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5492 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005493 mTouchModePerDisplay.count(displayId) == 0
5494 ? "not set"
5495 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5496
Antonio Kantek15beb512022-06-13 22:35:41 +00005497 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5498 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005499 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005500 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005501 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005502 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5503 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005504 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005505 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005506 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005507 return false;
5508 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005509 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005510 mTouchModePerDisplay[displayId] = inTouchMode;
5511 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5512 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005513 needWake = enqueueInboundEventLocked(std::move(entry));
5514 } // release lock
5515
5516 if (needWake) {
5517 mLooper->wake();
5518 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005519 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005520}
5521
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005522bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005523 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5524 if (focusedToken == nullptr) {
5525 return false;
5526 }
5527 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5528 return isWindowOwnedBy(windowHandle, pid, uid);
5529}
5530
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005531bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005532 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5533 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5534 const sp<WindowInfoHandle> windowHandle =
5535 getWindowHandleLocked(connectionToken);
5536 return isWindowOwnedBy(windowHandle, pid, uid);
5537 }) != mInteractionConnectionTokens.end();
5538}
5539
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005540void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5541 if (opacity < 0 || opacity > 1) {
5542 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5543 return;
5544 }
5545
5546 std::scoped_lock lock(mLock);
5547 mMaximumObscuringOpacityForTouch = opacity;
5548}
5549
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005550std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5551InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005552 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5553 for (TouchedWindow& w : state.windows) {
5554 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005555 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005556 }
5557 }
5558 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005559 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005560}
5561
Prabir Pradhan367f3432024-02-13 23:05:58 +00005562bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5563 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005564 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005565 if (DEBUG_FOCUS) {
5566 ALOGD("Trivial transfer to same window.");
5567 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005568 return true;
5569 }
5570
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005572 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573
Arthur Hungabbb9d82021-09-01 14:52:30 +00005574 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005575 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005576
Arthur Hungabbb9d82021-09-01 14:52:30 +00005577 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005578 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 return false;
5580 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005581 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5582 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005583 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5584 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005585 return false;
5586 }
5587 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005588
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005589 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5590 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5591 if (!toWindowHandle) {
5592 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005593 return false;
5594 }
5595
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005596 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005597 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598 touchedWindow->windowHandle->getName().c_str(),
5599 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 }
5601
Arthur Hungabbb9d82021-09-01 14:52:30 +00005602 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005603 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005604 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005605 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
Arthur Hungabbb9d82021-09-01 14:52:30 +00005607 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005608 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005609 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005610 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005611 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005612 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005613 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005614 // Transferring touch focus using this API should not effect the focused window.
5615 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005616 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005617 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618
Arthur Hungabbb9d82021-09-01 14:52:30 +00005619 // Store the dragging window.
5620 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005621 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005622 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5623 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005624 return false;
5625 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005626 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005627 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005628 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 }
5630
Arthur Hungabbb9d82021-09-01 14:52:30 +00005631 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005632 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5633 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005634 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005635 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005636 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5637 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005638 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005639 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5640 newTargetFlags);
5641
5642 // Check if the wallpaper window should deliver the corresponding event.
5643 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005644 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 } // release lock
5647
5648 // Wake up poll loop since it may need to make new input dispatching choices.
5649 mLooper->wake();
5650 return true;
5651}
5652
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005653/**
5654 * Get the touched foreground window on the given display.
5655 * Return null if there are no windows touched on that display, or if more than one foreground
5656 * window is being touched.
5657 */
5658sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5659 auto stateIt = mTouchStatesByDisplay.find(displayId);
5660 if (stateIt == mTouchStatesByDisplay.end()) {
5661 ALOGI("No touch state on display %" PRId32, displayId);
5662 return nullptr;
5663 }
5664
5665 const TouchState& state = stateIt->second;
5666 sp<WindowInfoHandle> touchedForegroundWindow;
5667 // If multiple foreground windows are touched, return nullptr
5668 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005669 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005670 if (touchedForegroundWindow != nullptr) {
5671 ALOGI("Two or more foreground windows: %s and %s",
5672 touchedForegroundWindow->getName().c_str(),
5673 window.windowHandle->getName().c_str());
5674 return nullptr;
5675 }
5676 touchedForegroundWindow = window.windowHandle;
5677 }
5678 }
5679 return touchedForegroundWindow;
5680}
5681
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005682// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005683bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5684 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005685 sp<IBinder> fromToken;
5686 { // acquire lock
5687 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005688 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005689 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005690 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5691 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005692 return false;
5693 }
5694
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005695 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5696 if (from == nullptr) {
5697 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5698 return false;
5699 }
5700
5701 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005702 } // release lock
5703
Prabir Pradhan367f3432024-02-13 23:05:58 +00005704 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005705}
5706
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005708 if (DEBUG_FOCUS) {
5709 ALOGD("Resetting and dropping all events (%s).", reason);
5710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711
Michael Wrightfb04fd52022-11-24 22:31:11 +00005712 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 synthesizeCancelationEventsForAllConnectionsLocked(options);
5714
5715 resetKeyRepeatLocked();
5716 releasePendingEventLocked();
5717 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005718 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005720 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005721 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722}
5723
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005724void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005725 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 dumpDispatchStateLocked(dump);
5727
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005728 std::istringstream stream(dump);
5729 std::string line;
5730
5731 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005732 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 }
5734}
5735
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005736std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005737 std::string dump;
5738
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005739 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5740 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005741
5742 std::string windowName = "None";
5743 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005744 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005745 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5746 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5747 : "token has capture without window";
5748 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005749 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005750
5751 return dump;
5752}
5753
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005754void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005755 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5756 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5757 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005758 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759
Tiger Huang721e26f2018-07-24 22:26:19 +08005760 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5761 dump += StringPrintf(INDENT "FocusedApplications:\n");
5762 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5763 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005764 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005765 const std::chrono::duration timeout =
5766 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005767 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005768 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005769 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005772 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005774
Vishnu Nairc519ff72021-01-21 08:23:08 -08005775 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005776 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005778 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005779 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005780 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005781 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5782 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005785 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 }
5787
arthurhung6d4bed92021-03-17 11:59:33 +08005788 if (mDragState) {
5789 dump += StringPrintf(INDENT "DragState:\n");
5790 mDragState->dump(dump, INDENT2);
5791 }
5792
Arthur Hungb92218b2018-08-14 12:00:21 +08005793 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005794 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5795 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5796 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5797 const auto& displayInfo = it->second;
5798 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5799 displayInfo.logicalHeight);
5800 displayInfo.transform.dump(dump, "transform", INDENT4);
5801 } else {
5802 dump += INDENT2 "No DisplayInfo found!\n";
5803 }
5804
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005805 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005806 dump += INDENT2 "Windows:\n";
5807 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005808 dump += StringPrintf(INDENT3 "%zu: %s", i,
5809 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005810 }
5811 } else {
5812 dump += INDENT2 "Windows: <none>\n";
5813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005816 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005819 if (!mGlobalMonitorsByDisplay.empty()) {
5820 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5821 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005822 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005825 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 }
5827
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005828 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829
5830 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005831 if (!mRecentQueue.empty()) {
5832 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005833 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005834 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005835 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005836 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005839 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 }
5841
5842 // Dump event currently being dispatched.
5843 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005844 dump += INDENT "PendingEvent:\n";
5845 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005846 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005847 dump += StringPrintf(", age=%" PRId64 "ms\n",
5848 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005850 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 }
5852
5853 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005854 if (!mInboundQueue.empty()) {
5855 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005856 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005857 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005858 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005859 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005862 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 }
5864
Prabir Pradhancef936d2021-07-21 16:17:52 +00005865 if (!mCommandQueue.empty()) {
5866 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5867 } else {
5868 dump += INDENT "CommandQueue: <empty>\n";
5869 }
5870
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005871 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005872 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005873 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005874 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005875 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005876 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005877 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005878 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005879 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005881 if (!connection->outboundQueue.empty()) {
5882 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5883 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005884 dump += dumpQueue(connection->outboundQueue, currentTime);
5885
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005887 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 }
5889
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005890 if (!connection->waitQueue.empty()) {
5891 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5892 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005893 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005895 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005897 std::string inputStateDump = streamableToString(connection->inputState);
5898 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005899 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005900 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 }
5903 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005904 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 }
5906
Antonio Kantek15beb512022-06-13 22:35:41 +00005907 if (!mTouchModePerDisplay.empty()) {
5908 dump += INDENT "TouchModePerDisplay:\n";
5909 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5910 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5911 std::to_string(touchMode).c_str());
5912 }
5913 } else {
5914 dump += INDENT "TouchModePerDisplay: <none>\n";
5915 }
5916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005917 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005918 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5919 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5920 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005921 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005922 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005923 dump += INDENT "InputTracer: ";
5924 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925}
5926
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005927void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005928 const size_t numMonitors = monitors.size();
5929 for (size_t i = 0; i < numMonitors; i++) {
5930 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005931 const std::shared_ptr<Connection>& connection = monitor.connection;
5932 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 dump += "\n";
5934 }
5935}
5936
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005937class LooperEventCallback : public LooperCallback {
5938public:
5939 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5940 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5941
5942private:
5943 std::function<int(int events)> mCallback;
5944};
5945
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005946Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005947 if (DEBUG_CHANNEL_CREATION) {
5948 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005951 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005952 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005953 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005954
5955 if (result) {
5956 return base::Error(result) << "Failed to open input channel pair with name " << name;
5957 }
5958
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005960 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005961 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005962 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005963 std::shared_ptr<Connection> connection =
5964 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5965 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005967 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5968 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005969 ALOGE("Created a new connection, but the token %p is already known", token.get());
5970 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005971
5972 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5973 this, std::placeholders::_1, token);
5974
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005975 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005976 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 } // release lock
5978
5979 // Wake the looper because some connections have changed.
5980 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005981 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982}
5983
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005984Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005985 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005986 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005987 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005988 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005989 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005990 if (result) {
5991 return base::Error(result) << "Failed to open input channel pair with name " << name;
5992 }
5993
Michael Wright3dd60e22019-03-27 22:06:44 +00005994 { // acquire lock
5995 std::scoped_lock _l(mLock);
5996
5997 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005998 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5999 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00006000 }
6001
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006002 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006003 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006004 std::shared_ptr<Connection> connection =
6005 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6006 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006007
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006008 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6009 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006010 ALOGE("Created a new connection, but the token %p is already known", token.get());
6011 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006012
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006013 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6014 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006015
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006016 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006017
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006018 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006019 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006020 }
Garfield Tan15601662020-09-22 15:32:38 -07006021
Michael Wright3dd60e22019-03-27 22:06:44 +00006022 // Wake the looper because some connections have changed.
6023 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006024 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006025}
6026
Garfield Tan15601662020-09-22 15:32:38 -07006027status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006029 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030
Harry Cutts33476232023-01-30 19:57:29 +00006031 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 if (status) {
6033 return status;
6034 }
6035 } // release lock
6036
6037 // Wake the poll loop because removing the connection may have changed the current
6038 // synchronization state.
6039 mLooper->wake();
6040 return OK;
6041}
6042
Garfield Tan15601662020-09-22 15:32:38 -07006043status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6044 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006045 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006046 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006047 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 return BAD_VALUE;
6049 }
6050
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006051 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006052
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006054 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 }
6056
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006057 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006058
6059 nsecs_t currentTime = now();
6060 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6061
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006062 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063 return OK;
6064}
6065
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006066void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006067 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6068 auto& [displayId, monitors] = *it;
6069 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006070 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006072
Michael Wright3dd60e22019-03-27 22:06:44 +00006073 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006075 } else {
6076 ++it;
6077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078 }
6079}
6080
Michael Wright3dd60e22019-03-27 22:06:44 +00006081status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006083 return pilferPointersLocked(token);
6084}
Michael Wright3dd60e22019-03-27 22:06:44 +00006085
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006086status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006087 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6088 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006089 LOG(WARNING)
6090 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006091 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006092 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006093
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006094 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006095 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006096 LOG(WARNING)
6097 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6098 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006099 return BAD_VALUE;
6100 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006101 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006102 if (deviceIds.empty()) {
6103 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006104 return BAD_VALUE;
6105 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006106
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006107 for (const DeviceId deviceId : deviceIds) {
6108 TouchState& state = *statePtr;
6109 TouchedWindow& window = *windowPtr;
6110 // Send cancel events to all the input channels we're stealing from.
6111 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6112 "input channel stole pointer stream");
6113 options.deviceId = deviceId;
6114 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006115 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6116 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006117 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006118
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006119 std::string canceledWindows;
6120 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006121 if (w.windowHandle->getToken() != token) {
6122 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006123 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006124 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006125 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006126 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006127 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006128 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006129 << " is stealing input gesture for device " << deviceId << " from "
6130 << canceledWindows;
6131
6132 // Prevent the gesture from being sent to any other windows.
6133 // This only blocks relevant pointers to be sent to other windows
6134 window.addPilferingPointers(deviceId, pointerIds);
6135
6136 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006137 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006138 return OK;
6139}
6140
Prabir Pradhan99987712020-11-10 18:43:05 -08006141void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6142 { // acquire lock
6143 std::scoped_lock _l(mLock);
6144 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006145 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006146 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6147 windowHandle != nullptr ? windowHandle->getName().c_str()
6148 : "token without window");
6149 }
6150
Vishnu Nairc519ff72021-01-21 08:23:08 -08006151 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006152 if (focusedToken != windowToken) {
6153 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6154 enabled ? "enable" : "disable");
6155 return;
6156 }
6157
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006158 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006159 ALOGW("Ignoring request to %s Pointer Capture: "
6160 "window has %s requested pointer capture.",
6161 enabled ? "enable" : "disable", enabled ? "already" : "not");
6162 return;
6163 }
6164
Christine Franksb768bb42021-11-29 12:11:31 -08006165 if (enabled) {
6166 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6167 mIneligibleDisplaysForPointerCapture.end(),
6168 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6169 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6170 return;
6171 }
6172 }
6173
Prabir Pradhan99987712020-11-10 18:43:05 -08006174 setPointerCaptureLocked(enabled);
6175 } // release lock
6176
6177 // Wake the thread to process command entries.
6178 mLooper->wake();
6179}
6180
Christine Franksb768bb42021-11-29 12:11:31 -08006181void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6182 { // acquire lock
6183 std::scoped_lock _l(mLock);
6184 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6185 if (!isEligible) {
6186 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6187 }
6188 } // release lock
6189}
6190
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006191std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006192 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006193 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006194 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006195 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006196 }
6197 }
6198 }
6199 return std::nullopt;
6200}
6201
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006202std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6203 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006204 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006205 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006206 }
6207
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006208 for (const auto& [token, connection] : mConnectionsByToken) {
6209 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006210 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211 }
6212 }
Robert Carr4e670e52018-08-15 13:26:12 -07006213
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006214 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215}
6216
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006217std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006218 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006219 if (connection == nullptr) {
6220 return "<nullptr>";
6221 }
6222 return connection->getInputChannelName();
6223}
6224
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006225void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006226 mAnrTracker.eraseToken(connection->getToken());
6227 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006228}
6229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006231 const std::shared_ptr<Connection>& connection,
6232 uint32_t seq, bool handled,
6233 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006234 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006235 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006236
6237 { // Start critical section
6238 auto dispatchEntryIt =
6239 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6240 [seq](auto& e) { return e->seq == seq; });
6241 if (dispatchEntryIt == connection->waitQueue.end()) {
6242 return;
6243 }
6244
6245 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6246
6247 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6248 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006249 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006250 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6251 }
6252 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006253 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006254 dispatchEntry.deliveryTime, consumeTime, finishTime);
6255 }
6256
6257 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006258 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6259 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006260 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006261 }
6262 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006263
6264 // Dequeue the event and start the next cycle.
6265 // Because the lock might have been released, it is possible that the
6266 // contents of the wait queue to have been drained, so we need to double-check
6267 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006268 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6269 [seq](auto& e) { return e->seq == seq; });
6270 if (entryIt != connection->waitQueue.end()) {
6271 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6272 connection->waitQueue.erase(entryIt);
6273
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006274 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6276 if (!connection->responsive) {
6277 connection->responsive = isConnectionResponsive(*connection);
6278 if (connection->responsive) {
6279 // The connection was unresponsive, and now it's responsive.
6280 processConnectionResponsiveLocked(*connection);
6281 }
6282 }
6283 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006284 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006285 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6286 // Only dispatch fallbacks if there is a window for the connection.
6287 if (windowHandle != nullptr) {
6288 const auto inputTarget =
6289 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6290 dispatchEntry->targetFlags,
6291 fallbackKeyEntry->downTime);
6292 if (inputTarget.has_value()) {
6293 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6294 *inputTarget);
6295 }
6296 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006297 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006298 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006299 }
6300
6301 // Start the next dispatch cycle for this connection.
6302 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303}
6304
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6306 const sp<IBinder>& newToken) {
6307 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6308 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006309 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006310 };
6311 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312}
6313
Prabir Pradhancef936d2021-07-21 16:17:52 +00006314void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6315 auto command = [this, token, x, y]() REQUIRES(mLock) {
6316 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006317 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006318 };
6319 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006320}
6321
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006322void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006323 if (connection == nullptr) {
6324 LOG_ALWAYS_FATAL("Caller must check for nullness");
6325 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006326 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6327 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006328 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006329 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006330 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006331 return;
6332 }
6333 /**
6334 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6335 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6336 * has changed. This could cause newer entries to time out before the already dispatched
6337 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6338 * processes the events linearly. So providing information about the oldest entry seems to be
6339 * most useful.
6340 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006341 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6342 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006343 std::string reason =
6344 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006345 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006347 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006348 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006349 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006350
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006351 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6352
6353 // Stop waking up for events on this connection, it is already unresponsive
6354 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006355}
6356
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006357void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6358 std::string reason =
6359 StringPrintf("%s does not have a focused window", application->getName().c_str());
6360 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006361
Yabin Cui8eb9c552023-06-08 18:05:07 +00006362 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006363 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006364 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006365 };
6366 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006367}
6368
chaviw98318de2021-05-19 16:45:23 -05006369void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006370 const std::string& reason) {
6371 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6372 updateLastAnrStateLocked(windowLabel, reason);
6373}
6374
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006375void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6376 const std::string& reason) {
6377 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006378 updateLastAnrStateLocked(windowLabel, reason);
6379}
6380
6381void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6382 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006384 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 struct tm tm;
6386 localtime_r(&t, &tm);
6387 char timestr[64];
6388 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006389 mLastAnrState.clear();
6390 mLastAnrState += INDENT "ANR:\n";
6391 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006392 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6393 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006394 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395}
6396
Prabir Pradhancef936d2021-07-21 16:17:52 +00006397void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006398 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006399 const KeyEvent event = createKeyEvent(entry);
6400 nsecs_t delay = 0;
6401 { // release lock
6402 scoped_unlock unlock(mLock);
6403 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006404 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006405 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6406 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6407 std::to_string(t.duration().count()).c_str());
6408 }
6409 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410
6411 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006412 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006413 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006414 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006416 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006417 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419}
6420
Prabir Pradhancef936d2021-07-21 16:17:52 +00006421void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006422 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006423 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006424 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006425 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006426 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006427 };
6428 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006429}
6430
Prabir Pradhanedd96402022-02-15 01:46:16 -08006431void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006432 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006433 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006434 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006435 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006436 };
6437 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006438}
6439
6440/**
6441 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6442 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6443 * command entry to the command queue.
6444 */
6445void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6446 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006447 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006448 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006449 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006450 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006451 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006452 pid = findMonitorPidByTokenLocked(connectionToken);
6453 } else {
6454 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006455 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006456 reason.c_str());
6457 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6458 if (handle != nullptr) {
6459 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006460 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006461 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006462 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006463}
6464
6465/**
6466 * Tell the policy that a connection has become responsive so that it can stop ANR.
6467 */
6468void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006469 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006470 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006471 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006472 pid = findMonitorPidByTokenLocked(connectionToken);
6473 } else {
6474 // The connection is a window
6475 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6476 if (handle != nullptr) {
6477 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006478 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006479 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006480 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006481}
6482
Prabir Pradhan24047542023-11-02 17:14:59 +00006483std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006484 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006485 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006487 if (!handled) {
6488 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006489 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006490 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006491 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494 // Get the fallback key state.
6495 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006496 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006498 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 connection->inputState.removeFallbackKey(originalKeyCode);
6500 }
6501
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006502 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 // If the application handles the original key for which we previously
6504 // generated a fallback or if the window is not a foreground window,
6505 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006506 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006508 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6509 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6510 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6511 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6512 keyEntry.policyFlags);
6513 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006514 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516
6517 mLock.unlock();
6518
Prabir Pradhana41d2442023-04-20 21:30:40 +00006519 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006520 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6521 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006522 unhandledKeyFallback) {
6523 event = *unhandledKeyFallback;
6524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006525
6526 mLock.lock();
6527
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006528 // Cancel the fallback key, but only if we still have a window for the channel.
6529 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006530 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006531 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6532 if (windowHandle != nullptr) {
6533 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6534 "application handled the original non-fallback key "
6535 "or is no longer a foreground target, "
6536 "canceling previously dispatched fallback key");
6537 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006538 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006541 connection->inputState.removeFallbackKey(originalKeyCode);
6542 }
6543 } else {
6544 // If the application did not handle a non-fallback key, first check
6545 // that we are in a good state to perform unhandled key event processing
6546 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006547 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006548 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006549 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6550 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6551 "since this is not an initial down. "
6552 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6553 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6554 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006555 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006559 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6560 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6561 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6562 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6563 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006564 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006565
6566 mLock.unlock();
6567
Prabir Pradhana41d2442023-04-20 21:30:40 +00006568 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006569 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6570 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006571 fb) {
6572 fallback = true;
6573 event = *fb;
6574 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006575
6576 mLock.lock();
6577
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006578 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006580 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 }
6582
6583 // Latch the fallback keycode for this key on an initial down.
6584 // The fallback keycode cannot change at any other point in the lifecycle.
6585 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006587 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006588 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006589 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006590 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006591 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006592 }
6593
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006594 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006595
6596 // Cancel the fallback key if the policy decides not to send it anymore.
6597 // We will continue to dispatch the key to the policy but we will no
6598 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006599 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6600 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006601 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6602 if (fallback) {
6603 ALOGD("Unhandled key event: Policy requested to send key %d"
6604 "as a fallback for %d, but on the DOWN it had requested "
6605 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006606 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006607 } else {
6608 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6609 "but on the DOWN it had requested to send %d. "
6610 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006611 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006612 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006613 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006614
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006615 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6616 if (windowHandle != nullptr) {
6617 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6618 "canceling fallback, policy no longer desires it");
6619 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006620 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006621 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006622
6623 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006624 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006625 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006626 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006627 }
6628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006629
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006630 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6631 {
6632 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006633 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006634 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006635 for (const auto& [key, value] : fallbackKeys) {
6636 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006637 }
6638 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6639 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006641 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006642
6643 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006644 // Return the fallback key that we want dispatched to the channel.
6645 std::unique_ptr<KeyEntry> newEntry =
6646 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6647 event.getEventTime(), event.getDeviceId(),
6648 event.getSource(), event.getDisplayId(),
6649 keyEntry.policyFlags, keyEntry.action,
6650 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6651 *fallbackKeyCode, event.getScanCode(),
6652 event.getMetaState(), event.getRepeatCount(),
6653 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006654 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6655 ALOGD("Unhandled key event: Dispatching fallback key. "
6656 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006657 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006658 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006659 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006660 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006661 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6662 ALOGD("Unhandled key event: No fallback key.");
6663 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006664
6665 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006666 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006667 }
6668 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006669 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670}
6671
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672void InputDispatcher::traceInboundQueueLengthLocked() {
6673 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006674 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675 }
6676}
6677
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006678void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006679 if (ATRACE_ENABLED()) {
6680 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006681 snprintf(counterName, sizeof(counterName), "oq:%s",
6682 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006683 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006684 }
6685}
6686
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006687void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688 if (ATRACE_ENABLED()) {
6689 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006690 snprintf(counterName, sizeof(counterName), "wq:%s",
6691 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006692 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 }
6694}
6695
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006696void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006697 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006698
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006699 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006700 dumpDispatchStateLocked(dump);
6701
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006702 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006703 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006704 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006705 }
6706}
6707
6708void InputDispatcher::monitor() {
6709 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006710 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006711 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006712 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006713}
6714
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006715/**
6716 * Wake up the dispatcher and wait until it processes all events and commands.
6717 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6718 * this method can be safely called from any thread, as long as you've ensured that
6719 * the work you are interested in completing has already been queued.
6720 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006721bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006722 /**
6723 * Timeout should represent the longest possible time that a device might spend processing
6724 * events and commands.
6725 */
6726 constexpr std::chrono::duration TIMEOUT = 100ms;
6727 std::unique_lock lock(mLock);
6728 mLooper->wake();
6729 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6730 return result == std::cv_status::no_timeout;
6731}
6732
Vishnu Naire798b472020-07-23 13:52:21 -07006733/**
6734 * Sets focus to the window identified by the token. This must be called
6735 * after updating any input window handles.
6736 *
6737 * Params:
6738 * request.token - input channel token used to identify the window that should gain focus.
6739 * request.focusedToken - the token that the caller expects currently to be focused. If the
6740 * specified token does not match the currently focused window, this request will be dropped.
6741 * If the specified focused token matches the currently focused window, the call will succeed.
6742 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6743 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6744 * when requesting the focus change. This determines which request gets
6745 * precedence if there is a focus change request from another source such as pointer down.
6746 */
Vishnu Nair958da932020-08-21 17:12:37 -07006747void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6748 { // acquire lock
6749 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006750 std::optional<FocusResolver::FocusChanges> changes =
6751 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6752 if (changes) {
6753 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006754 }
6755 } // release lock
6756 // Wake up poll loop since it may need to make new input dispatching choices.
6757 mLooper->wake();
6758}
6759
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006760void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6761 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006762 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006763 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6764 ? removedFocusedWindowHandle
6765 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6766 if (resolvedWindow == nullptr) {
6767 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006768 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006769 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6770 "focus left window");
6771 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6772 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006773 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006774 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006775 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006776 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006777 }
6778
Prabir Pradhan99987712020-11-10 18:43:05 -08006779 // If a window has pointer capture, then it must have focus. We need to ensure that this
6780 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6781 // If the window loses focus before it loses pointer capture, then the window can be in a state
6782 // where it has pointer capture but not focus, violating the contract. Therefore we must
6783 // dispatch the pointer capture event before the focus event. Since focus events are added to
6784 // the front of the queue (above), we add the pointer capture event to the front of the queue
6785 // after the focus events are added. This ensures the pointer capture event ends up at the
6786 // front.
6787 disablePointerCaptureForcedLocked();
6788
Vishnu Nairc519ff72021-01-21 08:23:08 -08006789 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006790 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006791 }
6792}
Vishnu Nair958da932020-08-21 17:12:37 -07006793
Prabir Pradhan99987712020-11-10 18:43:05 -08006794void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006795 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006796 return;
6797 }
6798
6799 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6800
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006801 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006802 setPointerCaptureLocked(false);
6803 }
6804
6805 if (!mWindowTokenWithPointerCapture) {
6806 // No need to send capture changes because no window has capture.
6807 return;
6808 }
6809
6810 if (mPendingEvent != nullptr) {
6811 // Move the pending event to the front of the queue. This will give the chance
6812 // for the pending event to be dropped if it is a captured event.
6813 mInboundQueue.push_front(mPendingEvent);
6814 mPendingEvent = nullptr;
6815 }
6816
6817 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006818 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006819 mInboundQueue.push_front(std::move(entry));
6820}
6821
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006822void InputDispatcher::setPointerCaptureLocked(bool enable) {
6823 mCurrentPointerCaptureRequest.enable = enable;
6824 mCurrentPointerCaptureRequest.seq++;
6825 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006826 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006827 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006828 };
6829 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006830}
6831
Vishnu Nair599f1412021-06-21 10:39:58 -07006832void InputDispatcher::displayRemoved(int32_t displayId) {
6833 { // acquire lock
6834 std::scoped_lock _l(mLock);
6835 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006836 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006837 setFocusedApplicationLocked(displayId, nullptr);
6838 // Call focus resolver to clean up stale requests. This must be called after input windows
6839 // have been removed for the removed display.
6840 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006841 // Reset pointer capture eligibility, regardless of previous state.
6842 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006843 // Remove the associated touch mode state.
6844 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006845 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006846 } // release lock
6847
6848 // Wake up poll loop since it may need to make new input dispatching choices.
6849 mLooper->wake();
6850}
6851
Patrick Williamsd828f302023-04-28 17:52:08 -05006852void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006853 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6854 {
6855 // acquire lock
6856 std::scoped_lock _l(mLock);
6857 logDispatchStateLocked();
6858 }
6859 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6860 result.error().message().c_str());
6861 };
chaviw15fab6f2021-06-07 14:15:52 -05006862 // The listener sends the windows as a flattened array. Separate the windows by display for
6863 // more convenient parsing.
6864 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006865 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006866 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006867 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006868 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006869
6870 { // acquire lock
6871 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006872
6873 // Ensure that we have an entry created for all existing displays so that if a displayId has
6874 // no windows, we can tell that the windows were removed from the display.
6875 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6876 handlesPerDisplay[displayId];
6877 }
6878
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006879 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006880 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006881 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6882 }
6883
6884 for (const auto& [displayId, handles] : handlesPerDisplay) {
6885 setInputWindowsLocked(handles, displayId);
6886 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006887
6888 if (update.vsyncId < mWindowInfosVsyncId) {
6889 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6890 ", current update vsync id: %" PRId64,
6891 mWindowInfosVsyncId, update.vsyncId);
6892 }
6893 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006894 }
6895 // Wake up poll loop since it may need to make new input dispatching choices.
6896 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006897}
6898
Vishnu Nair062a8672021-09-03 16:07:44 -07006899bool InputDispatcher::shouldDropInput(
6900 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006901 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6902 (windowHandle->getInfo()->inputConfig.test(
6903 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006904 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006905 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6906 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006907 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006908 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006909 windowHandle->getInfo()->displayId);
6910 return true;
6911 }
6912 return false;
6913}
6914
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006915void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006916 const gui::WindowInfosUpdate& update) {
6917 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006918}
6919
Arthur Hungdfd528e2021-12-08 13:23:04 +00006920void InputDispatcher::cancelCurrentTouch() {
6921 {
6922 std::scoped_lock _l(mLock);
6923 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006924 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006925 "cancel current touch");
6926 synthesizeCancelationEventsForAllConnectionsLocked(options);
6927
6928 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006929 }
6930 // Wake up poll loop since there might be work to do.
6931 mLooper->wake();
6932}
6933
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006934void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6935 std::scoped_lock _l(mLock);
6936 mMonitorDispatchingTimeout = timeout;
6937}
6938
Arthur Hungc539dbb2022-12-08 07:45:36 +00006939void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6940 const sp<WindowInfoHandle>& oldWindowHandle,
6941 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006942 TouchState& state, int32_t deviceId,
6943 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006944 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006945 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006946 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6947 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6948 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6949 newWindowHandle->getInfo()->inputConfig.test(
6950 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6951 const sp<WindowInfoHandle> oldWallpaper =
6952 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6953 const sp<WindowInfoHandle> newWallpaper =
6954 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6955 if (oldWallpaper == newWallpaper) {
6956 return;
6957 }
6958
6959 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006960 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006961 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006962 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006963 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006964 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006965 }
6966
6967 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006968 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6969 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006970 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006971 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006972 }
6973}
6974
6975void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6976 ftl::Flags<InputTarget::Flags> newTargetFlags,
6977 const sp<WindowInfoHandle> fromWindowHandle,
6978 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006979 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006980 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006981 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6982 fromWindowHandle->getInfo()->inputConfig.test(
6983 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6984 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6985 toWindowHandle->getInfo()->inputConfig.test(
6986 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6987
6988 const sp<WindowInfoHandle> oldWallpaper =
6989 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6990 const sp<WindowInfoHandle> newWallpaper =
6991 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6992 if (oldWallpaper == newWallpaper) {
6993 return;
6994 }
6995
6996 if (oldWallpaper != nullptr) {
6997 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6998 "transferring touch focus to another window");
6999 state.removeWindowByToken(oldWallpaper->getToken());
7000 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
7001 }
7002
7003 if (newWallpaper != nullptr) {
7004 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007005 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7006 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007007 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7008 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007009 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007010 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007011 std::shared_ptr<Connection> wallpaperConnection =
7012 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007013 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007014 std::shared_ptr<Connection> toConnection =
7015 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007016 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7017 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7018 wallpaperFlags);
7019 }
7020 }
7021}
7022
7023sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7024 const sp<WindowInfoHandle>& windowHandle) const {
7025 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7026 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7027 bool foundWindow = false;
7028 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7029 if (!foundWindow && otherHandle != windowHandle) {
7030 continue;
7031 }
7032 if (windowHandle == otherHandle) {
7033 foundWindow = true;
7034 continue;
7035 }
7036
7037 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7038 return otherHandle;
7039 }
7040 }
7041 return nullptr;
7042}
7043
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007044void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7045 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007046 std::scoped_lock _l(mLock);
7047
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007048 mConfig.keyRepeatTimeout = timeout.count();
7049 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007050}
7051
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007052bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7053 DeviceId deviceId, int32_t pointerId) {
7054 std::scoped_lock _l(mLock);
7055 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7056 if (touchStateIt == mTouchStatesByDisplay.end()) {
7057 return false;
7058 }
7059 for (const TouchedWindow& window : touchStateIt->second.windows) {
7060 if (window.windowHandle->getToken() == token &&
7061 (window.hasTouchingPointer(deviceId, pointerId) ||
7062 window.hasHoveringPointer(deviceId, pointerId))) {
7063 return true;
7064 }
7065 }
7066 return false;
7067}
7068
Garfield Tane84e6f92019-08-29 17:28:41 -07007069} // namespace android::inputdispatcher