blob: 3e999c702de3fdf5174a054c819879f2add2263f [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"
Michael Wright44753b12020-07-08 13:48:11 +010057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058#define INDENT " "
59#define INDENT2 " "
60#define INDENT3 " "
61#define INDENT4 " "
62
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080063using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070064using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080065using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000066using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070068using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050069using android::gui::FocusRequest;
70using android::gui::TouchOcclusionMode;
71using android::gui::WindowInfo;
72using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080073using android::os::InputEventInjectionResult;
74using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000075namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Prabir Pradhancef936d2021-07-21 16:17:52 +000079namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000080
Prabir Pradhandae52792023-12-15 07:36:40 +000081// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
82// flag is enabled. When the flag is changed, tracing will only be available after reboot.
83bool isInputTracingEnabled() {
84 static const std::string buildType = base::GetProperty("ro.build.type", "user");
85 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
86 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
87}
88
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000089template <class Entry>
90void ensureEventTraced(const Entry& entry) {
91 if (!entry.traceTracker) {
92 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
93 }
94}
95
Prabir Pradhancef936d2021-07-21 16:17:52 +000096// Temporarily releases a held mutex for the lifetime of the instance.
97// Named to match std::scoped_lock
98class scoped_unlock {
99public:
100 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
101 ~scoped_unlock() { mMutex.lock(); }
102
103private:
104 std::mutex& mMutex;
105};
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Default input dispatching timeout if there is no focused application or paused window
108// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800109const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
110 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
111 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800113// The default minimum time gap between two user activity poke events.
114const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
115
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800116const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// 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 +0000119constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
120
121// Log a warning when an interception call takes longer than this to process.
122constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123
124// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000125constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
126
Antonio Kantekea47acb2021-12-23 12:41:25 -0800127// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000128constexpr int LOGTAG_INPUT_INTERACTION = 62000;
129constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000130constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000131
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000132const ui::Transform kIdentityTransform;
133
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000134inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 return systemTime(SYSTEM_TIME_MONOTONIC);
136}
137
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700138inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000139 if (binder == nullptr) {
140 return "<null>";
141 }
142 return StringPrintf("%p", binder.get());
143}
144
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000145static std::string uidString(const gui::Uid& uid) {
146 return uid.toString();
147}
148
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700149Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700151 case AKEY_EVENT_ACTION_DOWN:
152 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700153 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157}
158
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159Result<void> validateKeyEvent(int32_t action) {
160 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161}
162
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800164 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_UP: {
167 if (pointerCount != 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
176 if (pointerCount < 1) {
177 return Error() << "invalid pointer count " << pointerCount;
178 }
179 return {};
180 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800181 case AMOTION_EVENT_ACTION_CANCEL:
182 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700184 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_POINTER_DOWN:
186 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800187 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700188 if (index < 0) {
189 return Error() << "invalid index " << index << " for "
190 << MotionEvent::actionToString(action);
191 }
192 if (index >= pointerCount) {
193 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
194 }
195 if (pointerCount <= 1) {
196 return Error() << "invalid pointer count " << pointerCount << " for "
197 << MotionEvent::actionToString(action);
198 }
199 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 }
201 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700202 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
203 if (actionButton == 0) {
204 return Error() << "action button should be nonzero for "
205 << MotionEvent::actionToString(action);
206 }
207 return {};
208 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700209 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700210 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212}
213
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000214int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500215 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
216}
217
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
219 const PointerProperties* pointerProperties) {
220 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
221 if (!actionCheck.ok()) {
222 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer count " << pointerCount
226 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 for (size_t i = 0; i < pointerCount; i++) {
230 int32_t id = pointerProperties[i].id;
231 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 return Error() << "Motion event has invalid pointer id " << id
233 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800235 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700236 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800238 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return {};
241}
242
243Result<void> validateInputEvent(const InputEvent& event) {
244 switch (event.getType()) {
245 case InputEventType::KEY: {
246 const KeyEvent& key = static_cast<const KeyEvent&>(event);
247 const int32_t action = key.getAction();
248 return validateKeyEvent(action);
249 }
250 case InputEventType::MOTION: {
251 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
252 const int32_t action = motion.getAction();
253 const size_t pointerCount = motion.getPointerCount();
254 const PointerProperties* pointerProperties = motion.getPointerProperties();
255 const int32_t actionButton = motion.getActionButton();
256 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
257 }
258 default: {
259 return {};
260 }
261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262}
263
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800264std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
265 std::bitset<MAX_POINTER_ID + 1> pointerIds;
266 for (const PointerProperties& pointer : pointers) {
267 pointerIds.set(pointer.id);
268 }
269 return pointerIds;
270}
271
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000274 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 }
276
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000277 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 bool first = true;
279 Region::const_iterator cur = region.begin();
280 Region::const_iterator const tail = region.end();
281 while (cur != tail) {
282 if (first) {
283 first = false;
284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800285 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800287 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 cur++;
289 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000290 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291}
292
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000293std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
294 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 constexpr size_t maxEntries = 50; // max events to print
296 constexpr size_t skipBegin = maxEntries / 2;
297 const size_t skipEnd = queue.size() - maxEntries / 2;
298 // skip from maxEntries / 2 ... size() - maxEntries/2
299 // only print from 0 .. skipBegin and then from skipEnd .. size()
300
301 std::string dump;
302 for (size_t i = 0; i < queue.size(); i++) {
303 const DispatchEntry& entry = *queue[i];
304 if (i >= skipBegin && i < skipEnd) {
305 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
306 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
307 continue;
308 }
309 dump.append(INDENT4);
310 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000311 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
312 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500313 ns2ms(currentTime - entry.eventEntry->eventTime));
314 if (entry.deliveryTime != 0) {
315 // This entry was delivered, so add information on how long we've been waiting
316 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
317 }
318 dump.append("\n");
319 }
320 return dump;
321}
322
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700323/**
324 * Find the entry in std::unordered_map by key, and return it.
325 * If the entry is not found, return a default constructed entry.
326 *
327 * Useful when the entries are vectors, since an empty vector will be returned
328 * if the entry is not found.
329 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
330 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700331template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700334 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800335}
336
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700338 if (first == second) {
339 return true;
340 }
341
342 if (first == nullptr || second == nullptr) {
343 return false;
344 }
345
346 return first->getToken() == second->getToken();
347}
348
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000349bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000350 if (first == nullptr || second == nullptr) {
351 return false;
352 }
353 return first->applicationInfo.token != nullptr &&
354 first->applicationInfo.token == second->applicationInfo.token;
355}
356
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800357template <typename T>
358size_t firstMarkedBit(T set) {
359 // TODO: replace with std::countr_zero from <bit> when that's available
360 LOG_ALWAYS_FATAL_IF(set.none());
361 size_t i = 0;
362 while (!set.test(i)) {
363 i++;
364 }
365 return i;
366}
367
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000368std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
369 std::shared_ptr<const EventEntry> eventEntry,
370 ftl::Flags<InputTarget::Flags> inputTargetFlags,
371 int64_t vsyncId) {
372 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
373 const std::optional<int32_t> windowId =
374 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
375 // Assume the only targets that are not associated with a window are global monitors, and use
376 // the system UID for global monitors for tracing purposes.
377 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 if (inputTarget.useDefaultPointerTransform()) {
379 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700380 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700381 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000382 inputTarget.globalScaleFactor, uid, vsyncId,
383 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384 }
385
386 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
387 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700390 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000391
392 // Use the first pointer information to normalize all other pointers. This could be any pointer
393 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700394 // uses the transform for the normalized pointer.
395 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800396 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700397 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398
399 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700400 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
402 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700403 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404
405 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700406 // First, apply the current pointer's transform to update the coordinates into
407 // window space.
408 pointerCoords[pointerIndex].transform(currTransform);
409 // Next, apply the inverse transform of the normalized coordinates so the
410 // current coordinates are transformed into the normalized coordinate space.
411 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412 }
413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700414 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000415 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
416 motionEntry.eventTime, motionEntry.deviceId,
417 motionEntry.source, motionEntry.displayId,
418 motionEntry.policyFlags, motionEntry.action,
419 motionEntry.actionButton, motionEntry.flags,
420 motionEntry.metaState, motionEntry.buttonState,
421 motionEntry.classification, motionEntry.edgeFlags,
422 motionEntry.xPrecision, motionEntry.yPrecision,
423 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
424 motionEntry.downTime, motionEntry.pointerProperties,
425 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000426
427 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700428 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700429 firstPointerTransform, inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000430 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431 return dispatchEntry;
432}
433
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500434template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500436 if (lhs == nullptr && rhs == nullptr) {
437 return true;
438 }
439 if (lhs == nullptr || rhs == nullptr) {
440 return false;
441 }
442 return *lhs == *rhs;
443}
444
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000445KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000446 KeyEvent event;
447 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
448 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
449 entry.repeatCount, entry.downTime, entry.eventTime);
450 return event;
451}
452
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 // Do not keep track of gesture monitors. They receive every event and would disproportionately
455 // affect the statistics.
456 if (connection.monitor) {
457 return false;
458 }
459 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
460 if (!connection.responsive) {
461 return false;
462 }
463 return true;
464}
465
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000466bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000467 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
468 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000469 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
470 return false;
471 }
472 // Only track latency for events that originated from hardware
473 if (eventEntry.isSynthesized()) {
474 return false;
475 }
476 const EventEntry::Type& inputEventEntryType = eventEntry.type;
477 if (inputEventEntryType == EventEntry::Type::KEY) {
478 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
479 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
480 return false;
481 }
482 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
483 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
484 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
485 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
486 return false;
487 }
488 } else {
489 // Not a key or a motion
490 return false;
491 }
492 if (!shouldReportMetricsForConnection(connection)) {
493 return false;
494 }
495 return true;
496}
497
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498/**
499 * Connection is responsive if it has no events in the waitQueue that are older than the
500 * current time.
501 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000502bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000503 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000504 for (const auto& dispatchEntry : connection.waitQueue) {
505 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000506 return false;
507 }
508 }
509 return true;
510}
511
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512// Returns true if the event type passed as argument represents a user activity.
513bool isUserActivityEvent(const EventEntry& eventEntry) {
514 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000515 case EventEntry::Type::CONFIGURATION_CHANGED:
516 case EventEntry::Type::DEVICE_RESET:
517 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::FOCUS:
519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000520 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000521 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000522 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000523 case EventEntry::Type::KEY:
524 case EventEntry::Type::MOTION:
525 return true;
526 }
527}
528
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000530bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000531 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800532 const auto inputConfig = windowInfo.inputConfig;
533 if (windowInfo.displayId != displayId ||
534 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800535 return false;
536 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700537 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800538 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800539 return false;
540 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000541
542 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
543 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
544 // the window. Points on the right and bottom edges should not be inside the window, so we need
545 // to be careful about performing a hit test when the display is rotated, since the "right" and
546 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
547 // logical display in which WM determined the bounds. Perform the hit test in the logical
548 // display space to ensure these edges are considered correctly in all orientations.
549 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
550 const auto p = displayTransform.transform(x, y);
551 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800552 return false;
553 }
554 return true;
555}
556
Prabir Pradhand65552b2021-10-07 11:23:50 -0700557bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
558 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000559 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700560}
561
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800562// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000563// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
564// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
565// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800566// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000567bool canReceiveForegroundTouches(const WindowInfo& info) {
568 // A non-touchable window can still receive touch events (e.g. in the case of
569 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
570 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
571}
572
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000573bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700574 if (windowHandle == nullptr) {
575 return false;
576 }
577 const WindowInfo* windowInfo = windowHandle->getInfo();
578 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
579 return true;
580 }
581 return false;
582}
583
Prabir Pradhan5735a322022-04-11 17:23:34 +0000584// Checks targeted injection using the window's owner's uid.
585// Returns an empty string if an entry can be sent to the given window, or an error message if the
586// entry is a targeted injection whose uid target doesn't match the window owner.
587std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
588 const EventEntry& entry) {
589 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
590 // The event was not injected, or the injected event does not target a window.
591 return {};
592 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000593 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000594 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000595 return StringPrintf("No valid window target for injection into uid %s.",
596 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000597 }
598 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000599 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
600 "owned by uid %s.",
601 uid.toString().c_str(), window->getName().c_str(),
602 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000603 }
604 return {};
605}
606
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
609 // Always dispatch mouse events to cursor position.
610 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000611 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612 }
613
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700614 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000615 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
616 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700617}
618
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700619std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
620 if (eventEntry.type == EventEntry::Type::KEY) {
621 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
622 return keyEntry.downTime;
623 } else if (eventEntry.type == EventEntry::Type::MOTION) {
624 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
625 return motionEntry.downTime;
626 }
627 return std::nullopt;
628}
629
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000630/**
631 * Compare the old touch state to the new touch state, and generate the corresponding touched
632 * windows (== input targets).
633 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
634 * If the pointer just entered the new window, produce HOVER_ENTER.
635 * For pointers remaining in the window, produce HOVER_MOVE.
636 */
637std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
638 const TouchState& newTouchState,
639 const MotionEntry& entry) {
640 std::vector<TouchedWindow> out;
641 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700642
643 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
644 // ACTION_SCROLL events should not affect the hovering pointer dispatch
645 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000646 }
647
648 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800649 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000650
651 std::set<sp<WindowInfoHandle>> oldWindows;
652 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800653 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000654 }
655
656 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800657 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658
659 // If the pointer is no longer in the new window set, send HOVER_EXIT.
660 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
661 if (newWindows.find(oldWindow) == newWindows.end()) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000664 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000665 out.push_back(touchedWindow);
666 }
667 }
668
669 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
670 TouchedWindow touchedWindow;
671 touchedWindow.windowHandle = newWindow;
672 if (oldWindows.find(newWindow) == oldWindows.end()) {
673 // Any windows that have this pointer now, and didn't have it before, should get
674 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000675 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 } else {
677 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700678 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700679 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000680 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
681 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700682 // The Accessibility injected touch exploration event stream
683 // has known inconsistencies, so log ERROR instead of
684 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700685 severity = android::base::LogSeverity::ERROR;
686 }
687 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700688 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000689 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000690 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800691 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000692 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
693 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
694 }
695 out.push_back(touchedWindow);
696 }
697 return out;
698}
699
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800700template <typename T>
701std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
702 left.insert(left.end(), right.begin(), right.end());
703 return left;
704}
705
Harry Cuttsb166c002023-05-09 13:06:05 +0000706// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
707// both.
708void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
709 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
710 if (!window.windowHandle->getInfo()->inputConfig.test(
711 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
712 // In addition to TouchState, erase this window from the input targets! We don't have a
713 // good way to do this today except by adding a nested loop.
714 // TODO(b/282025641): simplify this code once InputTargets are being identified
715 // separately from TouchedWindows.
716 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800717 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000718 });
719 return true;
720 }
721 return false;
722 });
723}
724
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700725/**
726 * In general, touch should be always split between windows. Some exceptions:
727 * 1. Don't split touch if all of the below is true:
728 * (a) we have an active pointer down *and*
729 * (b) a new pointer is going down that's from the same device *and*
730 * (c) the window that's receiving the current pointer does not support split touch.
731 * 2. Don't split mouse events
732 */
733bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
734 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
735 // We should never split mouse events
736 return false;
737 }
738 for (const TouchedWindow& touchedWindow : touchState.windows) {
739 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
740 // Spy windows should not affect whether or not touch is split.
741 continue;
742 }
743 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
744 continue;
745 }
746 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
747 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
748 // Wallpaper window should not affect whether or not touch is split
749 continue;
750 }
751
752 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
753 return false;
754 }
755 }
756 return true;
757}
758
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700759/**
760 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
761 */
762bool isStylusActiveInDisplay(
763 int32_t displayId,
764 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
765 const auto it = touchStatesByDisplay.find(displayId);
766 if (it == touchStatesByDisplay.end()) {
767 return false;
768 }
769 const TouchState& state = it->second;
770 return state.hasActiveStylus();
771}
772
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800773Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
774 struct HashFunction {
775 size_t operator()(const WindowInfo& info) const { return info.id; }
776 };
777
778 std::unordered_set<WindowInfo, HashFunction> windowSet;
779 for (const WindowInfo& info : update.windowInfos) {
780 const auto [_, inserted] = windowSet.insert(info);
781 if (!inserted) {
782 return Error() << "Duplicate entry for " << info;
783 }
784 }
785 return {};
786}
787
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800788int32_t getUserActivityEventType(const EventEntry& eventEntry) {
789 switch (eventEntry.type) {
790 case EventEntry::Type::KEY: {
791 return USER_ACTIVITY_EVENT_BUTTON;
792 }
793 case EventEntry::Type::MOTION: {
794 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
795 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
796 return USER_ACTIVITY_EVENT_TOUCH;
797 }
798 return USER_ACTIVITY_EVENT_OTHER;
799 }
800 default: {
801 LOG_ALWAYS_FATAL("%s events are not user activity",
802 ftl::enum_string(eventEntry.type).c_str());
803 }
804 }
805}
806
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000807std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
808 CancelationOptions::Mode mode) {
809 switch (mode) {
810 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
811 return {true, true};
812 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
813 return {true, false};
814 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
815 return {false, true};
816 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
817 return {false, true};
818 }
819}
820
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000821} // namespace
822
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823// --- InputDispatcher ---
824
Prabir Pradhana41d2442023-04-20 21:30:40 +0000825InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000826 : InputDispatcher(policy,
827 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
828 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000829
830InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
831 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700832 : mPolicy(policy),
833 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800835 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800836 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700837 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800838 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700839 mDispatchEnabled(false),
840 mDispatchFrozen(false),
841 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100842 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000843 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800844 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000845 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000846 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700847 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800848 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700850 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700851#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700852 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700853#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700854 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000855
856 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000857 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000858 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800859
860 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861}
862
863InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
Prabir Pradhancef936d2021-07-21 16:17:52 +0000866 resetKeyRepeatLocked();
867 releasePendingEventLocked();
868 drainInboundQueueLocked();
869 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000871 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700872 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800873 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875}
876
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700877status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700878 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700879 return ALREADY_EXISTS;
880 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700881 mThread = std::make_unique<InputThread>(
882 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
883 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700884}
885
886status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700887 if (mThread && mThread->isCallingThread()) {
888 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700889 return INVALID_OPERATION;
890 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700891 mThread.reset();
892 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700896 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800898 std::scoped_lock _l(mLock);
899 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 // Run a dispatch loop if there are no pending commands.
902 // The dispatch loop might enqueue commands to run afterwards.
903 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800904 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 // Run all pending commands if there are any.
908 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000909 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700910 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913 // If we are still waiting for ack on some events,
914 // we might have to wake up earlier to check if an app is anr'ing.
915 const nsecs_t nextAnrCheck = processAnrsLocked();
916 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
917
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800918 // We are about to enter an infinitely long sleep, because we have no commands or
919 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700920 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800921 mDispatcherEnteredIdle.notify_all();
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 } // release lock
924
925 // Wait for callback or timeout or wake. (make sure we round up, not down)
926 nsecs_t currentTime = now();
927 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
928 mLooper->pollOnce(timeoutMillis);
929}
930
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500932 * Raise ANR if there is no focused window.
933 * Before the ANR is raised, do a final state check:
934 * 1. The currently focused application must be the same one we are waiting for.
935 * 2. Ensure we still don't have a focused window.
936 */
937void InputDispatcher::processNoFocusedWindowAnrLocked() {
938 // Check if the application that we are waiting for is still focused.
939 std::shared_ptr<InputApplicationHandle> focusedApplication =
940 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
941 if (focusedApplication == nullptr ||
942 focusedApplication->getApplicationToken() !=
943 mAwaitedFocusedApplication->getApplicationToken()) {
944 // Unexpected because we should have reset the ANR timer when focused application changed
945 ALOGE("Waited for a focused window, but focused application has already changed to %s",
946 focusedApplication->getName().c_str());
947 return; // The focused application has changed.
948 }
949
chaviw98318de2021-05-19 16:45:23 -0500950 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500951 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
952 if (focusedWindowHandle != nullptr) {
953 return; // We now have a focused window. No need for ANR.
954 }
955 onAnrLocked(mAwaitedFocusedApplication);
956}
957
958/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 * Check if any of the connections' wait queues have events that are too old.
960 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
961 * Return the time at which we should wake up next.
962 */
963nsecs_t InputDispatcher::processAnrsLocked() {
964 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700965 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
967 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
968 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500969 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700970 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500971 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700972 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500974 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
976 }
977 }
978
979 // Check if any connection ANRs are due
980 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
981 if (currentTime < nextAnrCheck) { // most likely scenario
982 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
983 }
984
985 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700986 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700987 if (connection == nullptr) {
988 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
989 return nextAnrCheck;
990 }
991 connection->responsive = false;
992 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800993 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000994 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700995 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996}
997
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800998std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700999 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001000 if (connection->monitor) {
1001 return mMonitorDispatchingTimeout;
1002 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001003 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001005 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001006 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001007 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001008}
1009
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001010void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 nsecs_t currentTime = now();
1012
Jeff Browndc5992e2014-04-11 01:27:26 -07001013 // Reset the key repeat timer whenever normal dispatch is suspended while the
1014 // device is in a non-interactive state. This is to ensure that we abort a key
1015 // repeat if the device is just coming out of sleep.
1016 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 resetKeyRepeatLocked();
1018 }
1019
1020 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1021 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001022 if (DEBUG_FOCUS) {
1023 ALOGD("Dispatch frozen. Waiting some more.");
1024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 return;
1026 }
1027
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 // Ready to start a new event.
1029 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001031 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 // Synthesize a key repeat if appropriate.
1033 if (mKeyRepeatState.lastKeyEntry) {
1034 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1035 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1036 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001037 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039 }
1040
1041 // Nothing to do if there is no pending event.
1042 if (!mPendingEvent) {
1043 return;
1044 }
1045 } else {
1046 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001047 mPendingEvent = mInboundQueue.front();
1048 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 traceInboundQueueLengthLocked();
1050 }
1051
1052 // Poke user activity for this event.
1053 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001054 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057
1058 // Now we have an event to dispatch.
1059 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001060 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001062 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001064 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068
1069 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072
1073 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001074 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075 const ConfigurationChangedEntry& typedEntry =
1076 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 break;
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001082 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001083 const DeviceResetEntry& typedEntry =
1084 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 break;
1088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001090 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001091 std::shared_ptr<const FocusEntry> typedEntry =
1092 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001093 dispatchFocusLocked(currentTime, typedEntry);
1094 done = true;
1095 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1096 break;
1097 }
1098
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001099 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001100 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001101 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1102 done = true;
1103 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1104 break;
1105 }
1106
Prabir Pradhan99987712020-11-10 18:43:05 -08001107 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1108 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001109 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001110 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1111 done = true;
1112 break;
1113 }
1114
arthurhungb89ccb02020-12-30 16:19:01 +08001115 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001116 std::shared_ptr<const DragEntry> typedEntry =
1117 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001118 dispatchDragLocked(currentTime, typedEntry);
1119 done = true;
1120 break;
1121 }
1122
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001123 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001124 std::shared_ptr<const KeyEntry> keyEntry =
1125 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001127 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1130 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001132 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001133 if (done && mTracer) {
1134 ensureEventTraced(*keyEntry);
1135 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1136 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 break;
1138 }
1139
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001141 std::shared_ptr<const MotionEntry> motionEntry =
1142 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001144 // The event is stale. However, only drop stale events if there isn't an ongoing
1145 // gesture. That would allow us to complete the processing of the current stroke.
1146 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1147 if (touchStateIt != mTouchStatesByDisplay.end()) {
1148 const TouchState& touchState = touchStateIt->second;
1149 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1150 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1151 dropReason = DropReason::STALE;
1152 }
1153 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001156 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1157 // Only drop events that are focus-dispatched.
1158 dropReason = DropReason::BLOCKED;
1159 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001162 if (done && mTracer) {
1163 ensureEventTraced(*motionEntry);
1164 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
Chris Yef59a2f42020-10-16 12:55:26 -07001168
1169 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001170 std::shared_ptr<const SensorEntry> sensorEntry =
1171 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001172
Chris Yef59a2f42020-10-16 12:55:26 -07001173 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1174 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1175 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1176 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1177 dropReason = DropReason::STALE;
1178 }
1179 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1180 done = true;
1181 break;
1182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184
1185 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001186 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001187 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 }
Michael Wright3a981722015-06-10 15:26:13 +01001189 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190
1191 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001192 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194}
1195
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001196bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001197 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001198}
1199
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200/**
1201 * Return true if the events preceding this incoming motion event should be dropped
1202 * Return false otherwise (the default behaviour)
1203 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001204bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001205 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001206 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001207
1208 // Optimize case where the current application is unresponsive and the user
1209 // decides to touch a window in a different application.
1210 // If the application takes too long to catch up then we drop all events preceding
1211 // the touch into the other window.
1212 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001213 const int32_t displayId = motionEntry.displayId;
1214 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001215 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001216
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001217 sp<WindowInfoHandle> touchedWindowHandle =
1218 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001219 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220 touchedWindowHandle->getApplicationToken() !=
1221 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001223 ALOGI("Pruning input queue because user touched a different application while waiting "
1224 "for %s",
1225 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226 return true;
1227 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001228
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001229 // Alternatively, maybe there's a spy window that could handle this event.
1230 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1231 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1232 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001233 const std::shared_ptr<Connection> connection =
1234 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001235 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001236 // This spy window could take more input. Drop all events preceding this
1237 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001238 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001239 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 mAwaitedFocusedApplication->getName().c_str());
1241 return true;
1242 }
1243 }
1244 }
1245
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001246 return false;
1247}
1248
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001250 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001252 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 traceInboundQueueLengthLocked();
1254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001256 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001257 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1258 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001261 if (mTracer) {
1262 ensureEventTraced(keyEntry);
1263 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001264
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001265 // If a new up event comes in, and the pending event with same key code has been asked
1266 // to try again later because of the policy. We have to reset the intercept key wake up
1267 // time for it may have been handled in the policy and could be dropped.
1268 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1269 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001270 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001271 if (pendingKey.keyCode == keyEntry.keyCode &&
1272 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001273 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1274 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001275 pendingKey.interceptKeyWakeupTime = 0;
1276 needWake = true;
1277 }
1278 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 break;
1280 }
1281
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001282 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001283 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1284 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001285 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1286 if (mTracer) {
1287 ensureEventTraced(motionEntry);
1288 }
1289 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001291 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001293
1294 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1295 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1296 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1297 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1298 // and some other events have not yet been processed, the dispatcher will wait for
1299 // these events to be processed before dispatching the key event. This is because
1300 // the unprocessed events may cause the focus to change (for example, by launching a
1301 // new window or tapping a different window). To prevent waiting too long, we force
1302 // the key to be sent to the currently focused window when a new tap comes in.
1303 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1304 "just send the pending key event to the currently focused window.");
1305 mKeyIsWaitingForEventsTimeout = now();
1306 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001309 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001310 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1311 break;
1312 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001313 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001314 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001315 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001316 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001317 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1318 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001319 // nothing to do
1320 break;
1321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323
1324 return needWake;
1325}
1326
Prabir Pradhan24047542023-11-02 17:14:59 +00001327void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001328 // Do not store sensor event in recent queue to avoid flooding the queue.
1329 if (entry->type != EventEntry::Type::SENSOR) {
1330 mRecentQueue.push_back(entry);
1331 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001332 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001333 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335}
1336
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001337sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1338 bool isStylus,
1339 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001341 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001342 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001343 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001344 continue;
1345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001347 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001348 if (!info.isSpy() &&
1349 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001350 return windowHandle;
1351 }
1352 }
1353 return nullptr;
1354}
1355
1356std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001357 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001358 if (touchedWindow == nullptr) {
1359 return {};
1360 }
1361 // Traverse windows from front to back until we encounter the touched window.
1362 std::vector<InputTarget> outsideTargets;
1363 const auto& windowHandles = getWindowHandlesLocked(displayId);
1364 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1365 if (windowHandle == touchedWindow) {
1366 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1367 // below the touched window will not get ACTION_OUTSIDE event.
1368 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001369 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001370
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001371 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001372 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001373 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1374 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001375 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1376 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001377 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001380 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Prabir Pradhand65552b2021-10-07 11:23:50 -07001383std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001384 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001385 // Traverse windows from front to back and gather the touched spy windows.
1386 std::vector<sp<WindowInfoHandle>> spyWindows;
1387 const auto& windowHandles = getWindowHandlesLocked(displayId);
1388 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1389 const WindowInfo& info = *windowHandle->getInfo();
1390
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001391 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001392 continue;
1393 }
1394 if (!info.isSpy()) {
1395 // The first touched non-spy window was found, so return the spy windows touched so far.
1396 return spyWindows;
1397 }
1398 spyWindows.push_back(windowHandle);
1399 }
1400 return spyWindows;
1401}
1402
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001403void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 const char* reason;
1405 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001406 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001407 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001408 ALOGD("Dropped event because policy consumed it.");
1409 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 reason = "inbound event was dropped because the policy consumed it";
1411 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001412 case DropReason::DISABLED:
1413 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 ALOGI("Dropped event because input dispatch is disabled.");
1415 }
1416 reason = "inbound event was dropped because input dispatch is disabled";
1417 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001418 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001419 LOG(INFO) << "Dropping because the current application is not responding and the user "
1420 "has started interacting with a different application: "
1421 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 reason = "inbound event was dropped because the current application is not responding "
1423 "and the user has started interacting with a different application";
1424 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001425 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001426 ALOGI("Dropped event because it is stale.");
1427 reason = "inbound event was dropped because it is stale";
1428 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001429 case DropReason::NO_POINTER_CAPTURE:
1430 ALOGI("Dropped event because there is no window with Pointer Capture.");
1431 reason = "inbound event was dropped because there is no window with Pointer Capture";
1432 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001433 case DropReason::NOT_DROPPED: {
1434 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001440 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001441 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001442 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1443 options.displayId = keyEntry.displayId;
1444 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001448 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001449 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1450 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001451 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001452 options.displayId = motionEntry.displayId;
1453 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001454 synthesizeCancelationEventsForAllConnectionsLocked(options);
1455 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001456 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1457 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001458 options.displayId = motionEntry.displayId;
1459 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001460 synthesizeCancelationEventsForAllConnectionsLocked(options);
1461 }
1462 break;
1463 }
Chris Yef59a2f42020-10-16 12:55:26 -07001464 case EventEntry::Type::SENSOR: {
1465 break;
1466 }
arthurhungb89ccb02020-12-30 16:19:01 +08001467 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1468 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001469 break;
1470 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001471 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001472 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001473 case EventEntry::Type::CONFIGURATION_CHANGED:
1474 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001475 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001476 break;
1477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479}
1480
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001482 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483}
1484
Prabir Pradhancef936d2021-07-21 16:17:52 +00001485bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001486 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 return false;
1488 }
1489
1490 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001491 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001493 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1494 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001495 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 return true;
1497}
1498
Prabir Pradhancef936d2021-07-21 16:17:52 +00001499void InputDispatcher::postCommandLocked(Command&& command) {
1500 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501}
1502
1503void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001504 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001505 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001506 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 releaseInboundEventLocked(entry);
1508 }
1509 traceInboundQueueLengthLocked();
1510}
1511
1512void InputDispatcher::releasePendingEventLocked() {
1513 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001515 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
1517}
1518
Prabir Pradhan24047542023-11-02 17:14:59 +00001519void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001520 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001521 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001522 if (DEBUG_DISPATCH_CYCLE) {
1523 ALOGD("Injected inbound event was dropped.");
1524 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001525 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001528 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531}
1532
1533void InputDispatcher::resetKeyRepeatLocked() {
1534 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001535 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 }
1537}
1538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001539std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001540 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
Michael Wright2e732952014-09-24 13:26:59 -07001542 uint32_t policyFlags = entry->policyFlags &
1543 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001545 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001546 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1547 currentTime, entry->deviceId, entry->source,
1548 entry->displayId, policyFlags, entry->action, entry->flags,
1549 entry->keyCode, entry->scanCode, entry->metaState,
1550 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001552 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001553 if (mTracer) {
1554 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1555 }
1556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001557 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560}
1561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001562bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001564 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1565 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567
1568 // Reset key repeating in case a keyboard device was added or removed or something.
1569 resetKeyRepeatLocked();
1570
1571 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001572 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1573 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001574 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001575 };
1576 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return true;
1578}
1579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1581 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1584 entry.deviceId);
1585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586
liushenxiang42232912021-05-21 20:24:09 +08001587 // Reset key repeating in case a keyboard device was disabled or enabled.
1588 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1589 resetKeyRepeatLocked();
1590 }
1591
Michael Wrightfb04fd52022-11-24 22:31:11 +00001592 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001595
1596 // Remove all active pointers from this device
1597 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1598 touchState.removeAllPointersForDevice(entry.deviceId);
1599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 return true;
1601}
1602
Vishnu Nairad321cd2020-08-20 16:40:21 -07001603void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001604 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001605 if (mPendingEvent != nullptr) {
1606 // Move the pending event to the front of the queue. This will give the chance
1607 // for the pending event to get dispatched to the newly focused window
1608 mInboundQueue.push_front(mPendingEvent);
1609 mPendingEvent = nullptr;
1610 }
1611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001612 std::unique_ptr<FocusEntry> focusEntry =
1613 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1614 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001615
1616 // This event should go to the front of the queue, but behind all other focus events
1617 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001618 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1619 [](const std::shared_ptr<const EventEntry>& event) {
1620 return event->type == EventEntry::Type::FOCUS;
1621 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001622
1623 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001624 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001625}
1626
Prabir Pradhan24047542023-11-02 17:14:59 +00001627void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1628 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001629 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1630 if (connection == nullptr) {
1631 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001632 }
1633 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001634 target.connection = connection;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001635 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001636 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001637 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001638 std::string reason = std::string("reason=").append(entry->reason);
1639 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001640 dispatchEventLocked(currentTime, entry, {target});
1641}
1642
Prabir Pradhan99987712020-11-10 18:43:05 -08001643void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001644 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001645 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001646 dropReason = DropReason::NOT_DROPPED;
1647
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001649 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001650
1651 if (entry->pointerCaptureRequest.enable) {
1652 // Enable Pointer Capture.
1653 if (haveWindowWithPointerCapture &&
1654 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001655 // This can happen if pointer capture is disabled and re-enabled before we notify the
1656 // app of the state change, so there is no need to notify the app.
1657 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1658 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001659 }
1660 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001661 // This can happen if a window requests capture and immediately releases capture.
1662 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001663 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 return;
1665 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001666 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1667 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1668 return;
1669 }
1670
Vishnu Nairc519ff72021-01-21 08:23:08 -08001671 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001672 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1673 mWindowTokenWithPointerCapture = token;
1674 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001675 // Disable Pointer Capture.
1676 // We do not check if the sequence number matches for requests to disable Pointer Capture
1677 // for two reasons:
1678 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1679 // to disable capture with the same sequence number: one generated by
1680 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1681 // Capture being disabled in InputReader.
1682 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1683 // actual Pointer Capture state that affects events being generated by input devices is
1684 // in InputReader.
1685 if (!haveWindowWithPointerCapture) {
1686 // Pointer capture was already forcefully disabled because of focus change.
1687 dropReason = DropReason::NOT_DROPPED;
1688 return;
1689 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001690 token = mWindowTokenWithPointerCapture;
1691 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001692 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001693 setPointerCaptureLocked(false);
1694 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001695 }
1696
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001697 auto connection = getConnectionLocked(token);
1698 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001699 // Window has gone away, clean up Pointer Capture state.
1700 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001701 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001702 setPointerCaptureLocked(false);
1703 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001704 return;
1705 }
1706 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001707 target.connection = connection;
Prabir Pradhan99987712020-11-10 18:43:05 -08001708 entry->dispatchInProgress = true;
1709 dispatchEventLocked(currentTime, entry, {target});
1710
1711 dropReason = DropReason::NOT_DROPPED;
1712}
1713
Prabir Pradhan24047542023-11-02 17:14:59 +00001714void InputDispatcher::dispatchTouchModeChangeLocked(
1715 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001716 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001717 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001718 if (windowHandles.empty()) {
1719 return;
1720 }
1721 const std::vector<InputTarget> inputTargets =
1722 getInputTargetsFromWindowHandlesLocked(windowHandles);
1723 if (inputTargets.empty()) {
1724 return;
1725 }
1726 entry->dispatchInProgress = true;
1727 dispatchEventLocked(currentTime, entry, inputTargets);
1728}
1729
1730std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1731 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1732 std::vector<InputTarget> inputTargets;
1733 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001734 const sp<IBinder>& token = handle->getToken();
1735 if (token == nullptr) {
1736 continue;
1737 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001738 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1739 if (connection == nullptr) {
1740 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001741 }
1742 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001743 target.connection = connection;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001744 inputTargets.push_back(target);
1745 }
1746 return inputTargets;
1747}
1748
Prabir Pradhan24047542023-11-02 17:14:59 +00001749bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001750 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 if (!entry->dispatchInProgress) {
1753 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1754 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1755 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1756 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001757 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 // We have seen two identical key downs in a row which indicates that the device
1759 // driver is automatically generating key repeats itself. We take note of the
1760 // repeat here, but we disable our own next key repeat timer since it is clear that
1761 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001762 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1763 // Make sure we don't get key down from a different device. If a different
1764 // device Id has same key pressed down, the new device Id will replace the
1765 // current one to hold the key repeat with repeat count reset.
1766 // In the future when got a KEY_UP on the device id, drop it and do not
1767 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1769 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001770 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 } else {
1772 // Not a repeat. Save key down state in case we do see a repeat later.
1773 resetKeyRepeatLocked();
1774 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1775 }
1776 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001777 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1778 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001779 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001780 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1782 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001783 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 resetKeyRepeatLocked();
1785 }
1786
1787 if (entry->repeatCount == 1) {
1788 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1789 } else {
1790 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1791 }
1792
1793 entry->dispatchInProgress = true;
1794
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
1797
1798 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001799 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001801 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return false; // wait until next wakeup
1803 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001804 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 entry->interceptKeyWakeupTime = 0;
1806 }
1807
1808 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001809 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001811 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001812 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001813
1814 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1815 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1816 };
1817 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001818 // Poke user activity for keys not passed to user
1819 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 return false; // wait for the command to run
1821 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001822 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001824 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001825 if (*dropReason == DropReason::NOT_DROPPED) {
1826 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828 }
1829
1830 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001831 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001832 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001833 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1834 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001835 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001836 // Poke user activity for undispatched keys
1837 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 return true;
1839 }
1840
1841 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001842 InputEventInjectionResult injectionResult;
1843 sp<WindowInfoHandle> focusedWindow =
1844 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1845 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 return false;
1848 }
1849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001850 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 return true;
1853 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001854 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1855
1856 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001857 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1858 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001860 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001863 if (mTracer) {
1864 ensureEventTraced(*entry);
1865 for (const auto& target : inputTargets) {
1866 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1867 }
1868 }
1869
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 // Dispatch the key.
1871 dispatchEventLocked(currentTime, entry, inputTargets);
1872 return true;
1873}
1874
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001875void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001876 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1877 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1878 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1879 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1880 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1881 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1882 entry.metaState, entry.repeatCount, entry.downTime);
1883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884}
1885
Prabir Pradhancef936d2021-07-21 16:17:52 +00001886void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001887 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001888 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001889 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1890 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1891 "source=0x%x, sensorType=%s",
1892 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001893 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001894 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001895 auto command = [this, entry]() REQUIRES(mLock) {
1896 scoped_unlock unlock(mLock);
1897
1898 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001899 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001900 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001901 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1902 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001903 };
1904 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001905}
1906
1907bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001908 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1909 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001910 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001911 }
Chris Yef59a2f42020-10-16 12:55:26 -07001912 { // acquire lock
1913 std::scoped_lock _l(mLock);
1914
1915 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001916 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001917 if (entry->type == EventEntry::Type::SENSOR) {
1918 it = mInboundQueue.erase(it);
1919 releaseInboundEventLocked(entry);
1920 }
1921 }
1922 }
1923 return true;
1924}
1925
Prabir Pradhan24047542023-11-02 17:14:59 +00001926bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1927 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001928 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001929 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001931 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 entry->dispatchInProgress = true;
1933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001934 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 }
1936
1937 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001938 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001939 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1941 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 return true;
1943 }
1944
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001945 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
1947 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001948 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 if (isPointerEvent) {
1952 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001953
1954 if (mDragState &&
1955 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1956 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1957 pilferPointersLocked(mDragState->dragWindow->getToken());
1958 }
1959
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001960 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001961 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001962 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1963 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 } else {
1965 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001966 sp<WindowInfoHandle> focusedWindow =
1967 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1968 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1969 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001970 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1971 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1972 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001975 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 return false;
1977 }
1978
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001979 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001980 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001981 return true;
1982 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001984 CancelationOptions::Mode mode(
1985 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1986 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001988 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001989 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 return true;
1991 }
1992
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001993 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001994 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001996 if (mTracer) {
1997 ensureEventTraced(*entry);
1998 for (const auto& target : inputTargets) {
1999 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2000 }
2001 }
2002
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 dispatchEventLocked(currentTime, entry, inputTargets);
2005 return true;
2006}
2007
chaviw98318de2021-05-19 16:45:23 -05002008void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002009 bool isExiting, const int32_t rawX,
2010 const int32_t rawY) {
2011 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002012 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002013 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2014 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002015
2016 enqueueInboundEventLocked(std::move(dragEntry));
2017}
2018
Prabir Pradhan24047542023-11-02 17:14:59 +00002019void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2020 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002021 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2022 if (connection == nullptr) {
2023 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002024 }
2025 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002026 target.connection = connection;
arthurhungb89ccb02020-12-30 16:19:01 +08002027 entry->dispatchInProgress = true;
2028 dispatchEventLocked(currentTime, entry, {target});
2029}
2030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002032 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002033 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002034 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002035 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002036 "metaState=0x%x, buttonState=0x%x,"
2037 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002038 prefix, entry.eventTime, entry.deviceId,
2039 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2040 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2041 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2042 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002044 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002045 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002046 "x=%f, y=%f, pressure=%f, size=%f, "
2047 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2048 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002049 i, entry.pointerProperties[i].id,
2050 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002051 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2052 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2053 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2054 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2055 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2056 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2057 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2058 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2059 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062}
2063
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002064void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002065 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002068 if (DEBUG_DISPATCH_CYCLE) {
2069 ALOGD("dispatchEventToCurrentInputTargets");
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002072 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002073
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2075
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002078 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002079 std::shared_ptr<Connection> connection = inputTarget.connection;
2080 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082}
2083
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002084void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2086 // If the policy decides to close the app, we will get a channel removal event via
2087 // unregisterInputChannel, and will clean up the connection that way. We are already not
2088 // sending new pointers to the connection when it blocked, but focused events will continue to
2089 // pile up.
2090 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002091 connection->getInputChannelName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002092 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002093 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002094 "application not responding");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00002095 synthesizeCancelationEventsForConnectionLocked(connection, options,
2096 getWindowHandleLocked(
2097 connection->getToken()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
2099}
2100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002102 if (DEBUG_FOCUS) {
2103 ALOGD("Resetting ANR timeouts.");
2104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105
2106 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002108 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109}
2110
Tiger Huang721e26f2018-07-24 22:26:19 +08002111/**
2112 * Get the display id that the given event should go to. If this event specifies a valid display id,
2113 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2114 * Focused display is the display that the user most recently interacted with.
2115 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002116int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002117 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002118 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002119 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002120 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2121 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122 break;
2123 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002124 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002125 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2126 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 break;
2128 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002129 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002130 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002131 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002132 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002133 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002134 case EventEntry::Type::SENSOR:
2135 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002136 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 return ADISPLAY_ID_NONE;
2138 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002139 }
2140 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2141}
2142
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002143bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2144 const char* focusedWindowName) {
2145 if (mAnrTracker.empty()) {
2146 // already processed all events that we waited for
2147 mKeyIsWaitingForEventsTimeout = std::nullopt;
2148 return false;
2149 }
2150
2151 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2152 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002153 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002154 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002155 std::chrono::duration_cast<std::chrono::nanoseconds>(
2156 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002157 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002158 return true;
2159 }
2160
2161 // We still have pending events, and already started the timer
2162 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2163 return true; // Still waiting
2164 }
2165
2166 // Waited too long, and some connection still hasn't processed all motions
2167 // Just send the key to the focused window
2168 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2169 focusedWindowName);
2170 mKeyIsWaitingForEventsTimeout = std::nullopt;
2171 return false;
2172}
2173
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002174sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002175 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002176 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
Tiger Huang721e26f2018-07-24 22:26:19 +08002179 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002180 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002181 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002182 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2183
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 // If there is no currently focused window and no focused application
2185 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2187 ALOGI("Dropping %s event because there is no focused window or focused application in "
2188 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002189 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002190 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
2192
Vishnu Nair062a8672021-09-03 16:07:44 -07002193 // Drop key events if requested by input feature
2194 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002196 }
2197
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002198 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2199 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2200 // start interacting with another application via touch (app switch). This code can be removed
2201 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2202 // an app is expected to have a focused window.
2203 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2204 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2205 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002206 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2207 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2208 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002209 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002210 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002211 ALOGW("Waiting because no window has focus but %s may eventually add a "
2212 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002213 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002214 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002215 outInjectionResult = InputEventInjectionResult::PENDING;
2216 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002217 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2218 // Already raised ANR. Drop the event
2219 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002220 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002221 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002222 } else {
2223 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 outInjectionResult = InputEventInjectionResult::PENDING;
2225 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002226 }
2227 }
2228
2229 // we have a valid, non-null focused window
2230 resetNoFocusedWindowTimeoutLocked();
2231
Prabir Pradhan5735a322022-04-11 17:23:34 +00002232 // Verify targeted injection.
2233 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2234 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2236 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002239 if (focusedWindowHandle->getInfo()->inputConfig.test(
2240 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002242 outInjectionResult = InputEventInjectionResult::PENDING;
2243 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 }
2245
2246 // If the event is a key event, then we must wait for all previous events to
2247 // complete before delivering it because previous events may have the
2248 // side-effect of transferring focus to a different window and we want to
2249 // ensure that the following keys are sent to the new window.
2250 //
2251 // Suppose the user touches a button in a window then immediately presses "A".
2252 // If the button causes a pop-up window to appear then we want to ensure that
2253 // the "A" key is delivered to the new pop-up window. This is because users
2254 // often anticipate pending UI changes when typing on a keyboard.
2255 // To obtain this behavior, we must serialize key events with respect to all
2256 // prior input events.
2257 if (entry.type == EventEntry::Type::KEY) {
2258 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002259 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002260 outInjectionResult = InputEventInjectionResult::PENDING;
2261 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002265 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2266 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267}
2268
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269/**
2270 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2271 * that are currently unresponsive.
2272 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002273std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2274 const std::vector<Monitor>& monitors) const {
2275 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002276 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002277 [](const Monitor& monitor) REQUIRES(mLock) {
2278 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 if (!connection->responsive) {
2280 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002281 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 return false;
2283 }
2284 return true;
2285 });
2286 return responsiveMonitors;
2287}
2288
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002289std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002290 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002291 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002292 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002294 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 // For security reasons, we defer updating the touch state until we are sure that
2296 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002297 const int32_t displayId = entry.displayId;
2298 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002299 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002302 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002304 // Copy current touch state into tempTouchState.
2305 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2306 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002307 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002308 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2310 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002311 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002312 }
2313
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002314 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002315
2316 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2317 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2318 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002319 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2320 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002321 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002322 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2323 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002324 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2325 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002327 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002328
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002329 if (newGesture) {
2330 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002331 }
2332
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002333 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2334 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2335 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002338 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002339 if (wasDown) {
2340 // Started hovering, but the device is already down: reject the hover event
2341 LOG(ERROR) << "Got hover event " << entry.getDescription()
2342 << " but the device is already down " << oldState->dump();
2343 outInjectionResult = InputEventInjectionResult::FAILED;
2344 return {};
2345 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002346 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2347 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002348 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002349 }
2350
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2352 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002353 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002354 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002355 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002356 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2357 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002358 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002359 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002360 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002361
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002362 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002363 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002366 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002367 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002369 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002370 }
2371
Prabir Pradhan5735a322022-04-11 17:23:34 +00002372 // Verify targeted injection.
2373 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2374 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002375 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002376 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002377 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002378 }
2379
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002380 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002381 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002382 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2383 // New window supports splitting, but we should never split mouse events.
2384 isSplit = !isFromMouse;
2385 } else if (isSplit) {
2386 // New window does not support splitting but we have already split events.
2387 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002388 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2389 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002390 newTouchedWindowHandle = nullptr;
2391 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 } else {
2393 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002394 // be delivered to a new window which supports split touch. Pointers from a mouse device
2395 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002396 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002397 }
2398
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002399 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002400 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002402 // Process the foreground window first so that it is the first to receive the event.
2403 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 }
2405
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002406 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002407 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2408 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002409 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002410 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002411 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002412 }
2413
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002414 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002415 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002416 continue;
2417 }
2418
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002419 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002420 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002421 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002422 }
2423
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002425 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002426
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002427 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2428 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002429 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002430 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002431
2432 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002433 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434 }
2435 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002436 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002437 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002438 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002439 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002440
2441 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002442
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002443 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002444 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2445 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002446 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002447 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002448 isDownOrPointerDown
2449 ? std::make_optional(entry.eventTime)
2450 : std::nullopt);
2451 // If this is the pointer going down and the touched window has a wallpaper
2452 // then also add the touched wallpaper windows so they are locked in for the
2453 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2454 // SCROLL because the wallpaper engine only supports touch events. We would need to
2455 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2456 // handle these events.
2457 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002458 windowHandle->getInfo()->inputConfig.test(
2459 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2460 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2461 if (wallpaper != nullptr) {
2462 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2463 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002464 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002465 if (isSplit) {
2466 wallpaperFlags |= InputTarget::Flags::SPLIT;
2467 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002468 tempTouchState.addOrUpdateWindow(wallpaper,
2469 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002470 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002471 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002472 }
2473 }
2474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002476
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002477 // If a window is already pilfering some pointers, give it this new pointer as well and
2478 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2479 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002480 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002481 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002482 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002483 // This window is already pilfering some pointers, and this new pointer is also
2484 // going to it. Therefore, take over this pointer and don't give it to anyone
2485 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002486 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002487 }
2488 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002489
2490 // Restrict all pilfered pointers to the pilfering windows.
2491 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 } else {
2493 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2494
2495 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002496 if (!tempTouchState.isDown(entry.deviceId) &&
2497 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002498 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2499 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2500 << " is not down or we previously dropped the pointer down event in "
2501 << "display " << displayId << ": " << entry.getDescription();
2502 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002503 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002504 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002507 // If the pointer is not currently hovering, then ignore the event.
2508 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2509 const int32_t pointerId = entry.pointerProperties[0].id;
2510 if (oldState == nullptr ||
2511 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2512 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2513 "display "
2514 << displayId << ": " << entry.getDescription();
2515 outInjectionResult = InputEventInjectionResult::FAILED;
2516 return {};
2517 }
2518 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2519 }
2520
arthurhung6d4bed92021-03-17 11:59:33 +08002521 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002522
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002524 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002525 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002526 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002527 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002528 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002529 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002530 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002531 sp<WindowInfoHandle> newTouchedWindowHandle =
2532 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002533
Prabir Pradhan5735a322022-04-11 17:23:34 +00002534 // Verify targeted injection.
2535 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2536 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002537 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002538 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002539 }
2540
Vishnu Nair062a8672021-09-03 16:07:44 -07002541 // Drop touch events if requested by input feature
2542 if (newTouchedWindowHandle != nullptr &&
2543 shouldDropInput(entry, newTouchedWindowHandle)) {
2544 newTouchedWindowHandle = nullptr;
2545 }
2546
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002547 if (newTouchedWindowHandle != nullptr &&
2548 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002549 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002550 oldTouchedWindowHandle->getName().c_str(),
2551 newTouchedWindowHandle->getName().c_str(), displayId);
2552
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002554 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002555 const PointerProperties& pointer = entry.pointerProperties[0];
2556 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002557
2558 const TouchedWindow& touchedWindow =
2559 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002560 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002561 InputTarget::DispatchMode::SLIPPERY_EXIT,
2562 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002563 touchedWindow.getDownTimeInTarget(entry.deviceId),
2564 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565
2566 // Make a slippery entrance into the new window.
2567 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002568 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002571 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002572 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002573 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002576 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
2578 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002579 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002580 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002581 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002584 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2585 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002586 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002587 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002588
2589 // Check if the wallpaper window should deliver the corresponding event.
2590 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002591 tempTouchState, entry.deviceId, pointer, targets);
2592 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002593 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 }
2595 }
Arthur Hung96483742022-11-15 03:30:48 +00002596
2597 // Update the pointerIds for non-splittable when it received pointer down.
2598 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2599 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002600 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002601 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2602 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002603 // Ignore drag window for it should just track one pointer.
2604 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2605 continue;
2606 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002607 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002608 }
2609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
2611
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002612 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002613 {
2614 std::vector<TouchedWindow> hoveringWindows =
2615 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2616 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002617 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002618 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2619 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002620 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002621 if (!target) {
2622 continue;
2623 }
2624 // Hardcode to single hovering pointer for now.
2625 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2626 pointerIds.set(entry.pointerProperties[0].id);
2627 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2628 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631
Prabir Pradhan5735a322022-04-11 17:23:34 +00002632 // Ensure that all touched windows are valid for injection.
2633 if (entry.injectionState != nullptr) {
2634 std::string errs;
2635 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002636 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2637 if (err) errs += "\n - " + *err;
2638 }
2639 if (!errs.empty()) {
2640 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002641 "%s:%s",
2642 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002643 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002644 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002645 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002646 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002647
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002648 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2649 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002651 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002652 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002653 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002654 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002655 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002656 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002657 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002658 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002659 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2660 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 }
2663 }
2664 }
2665 }
2666
Harry Cuttsb166c002023-05-09 13:06:05 +00002667 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2668 // only want the system UI to handle these gestures.
2669 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2670 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2671 if (isTouchpadNavGesture) {
2672 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2673 }
2674
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002675 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002676 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002677 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002678 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002679 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002680 continue;
2681 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002682 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002683 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002684 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002685 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002686
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002687 // During targeted injection, only allow owned targets to receive events
2688 std::erase_if(targets, [&](const InputTarget& target) {
2689 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2690 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2691 if (err) {
2692 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2693 << ": " << (*err);
2694 return true;
2695 }
2696 return false;
2697 });
2698
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002699 if (targets.empty()) {
2700 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2701 outInjectionResult = InputEventInjectionResult::FAILED;
2702 return {};
2703 }
2704
2705 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2706 // window that is actually receiving the entire gesture.
2707 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002708 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002709 })) {
2710 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2711 << entry.getDescription();
2712 outInjectionResult = InputEventInjectionResult::FAILED;
2713 return {};
2714 }
2715
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002716 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717
Prabir Pradhan502a7252023-12-01 16:11:24 +00002718 // Now that we have generated all of the input targets for this event, reset the dispatch
2719 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002720 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002721 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 }
2723
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002724 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002725 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002726 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002727 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002729 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002730 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2732 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002733 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2734 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2735 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002738 // Save changes unless the action was scroll in which case the temporary touch
2739 // state was only valid for this one action.
2740 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002741 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002742 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002743 mTouchStatesByDisplay[displayId] = tempTouchState;
2744 } else {
2745 mTouchStatesByDisplay.erase(displayId);
2746 }
2747 }
2748
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002749 if (tempTouchState.windows.empty()) {
2750 mTouchStatesByDisplay.erase(displayId);
2751 }
2752
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002753 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754}
2755
arthurhung6d4bed92021-03-17 11:59:33 +08002756void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002757 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2758 // have an explicit reason to support it.
2759 constexpr bool isStylus = false;
2760
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002761 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002762 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002763 if (dropWindow) {
2764 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002765 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002766 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002767 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002768 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002769 }
2770 mDragState.reset();
2771}
2772
2773void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002774 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002775 return;
2776 }
2777
arthurhung6d4bed92021-03-17 11:59:33 +08002778 if (!mDragState->isStartDrag) {
2779 mDragState->isStartDrag = true;
2780 mDragState->isStylusButtonDownAtStart =
2781 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2782 }
2783
Arthur Hung54745652022-04-20 07:17:41 +00002784 // Find the pointer index by id.
2785 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002786 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002787 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2788 if (pointerProperties.id == mDragState->pointerId) {
2789 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002790 }
Arthur Hung54745652022-04-20 07:17:41 +00002791 }
arthurhung6d4bed92021-03-17 11:59:33 +08002792
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002793 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002794 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002795 }
2796
2797 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2798 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2799 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2800
2801 switch (maskedAction) {
2802 case AMOTION_EVENT_ACTION_MOVE: {
2803 // Handle the special case : stylus button no longer pressed.
2804 bool isStylusButtonDown =
2805 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2806 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2807 finishDragAndDrop(entry.displayId, x, y);
2808 return;
2809 }
2810
2811 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2812 // until we have an explicit reason to support it.
2813 constexpr bool isStylus = false;
2814
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002815 sp<WindowInfoHandle> hoverWindowHandle =
2816 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2817 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002818 // enqueue drag exit if needed.
2819 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2820 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2821 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002822 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002823 y);
2824 }
2825 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2826 }
2827 // enqueue drag location if needed.
2828 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002829 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002830 }
2831 break;
2832 }
2833
2834 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002835 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002836 break;
2837 }
2838 // The drag pointer is up.
2839 [[fallthrough]];
2840 case AMOTION_EVENT_ACTION_UP:
2841 finishDragAndDrop(entry.displayId, x, y);
2842 break;
2843 case AMOTION_EVENT_ACTION_CANCEL: {
2844 ALOGD("Receiving cancel when drag and drop.");
2845 sendDropWindowCommandLocked(nullptr, 0, 0);
2846 mDragState.reset();
2847 break;
2848 }
arthurhungb89ccb02020-12-30 16:19:01 +08002849 }
2850}
2851
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002852std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2853 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002854 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002855 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002856 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2857 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2859 return {};
2860 }
2861 InputTarget inputTarget;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002862 inputTarget.connection = connection;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002863 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002864 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002865 inputTarget.flags = targetFlags;
2866 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2867 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2868 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2869 if (displayInfoIt != mDisplayInfos.end()) {
2870 inputTarget.displayTransform = displayInfoIt->second.transform;
2871 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002872 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002873 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2874 }
2875 return inputTarget;
2876}
2877
chaviw98318de2021-05-19 16:45:23 -05002878void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002879 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002880 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002881 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002882 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883 std::vector<InputTarget>::iterator it =
2884 std::find_if(inputTargets.begin(), inputTargets.end(),
2885 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002886 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002887 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002888
chaviw98318de2021-05-19 16:45:23 -05002889 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002890
2891 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002892 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002893 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2894 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002895 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002896 return;
2897 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002898 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002899 it = inputTargets.end() - 1;
2900 }
2901
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002902 if (it->flags != targetFlags) {
2903 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2904 }
2905 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2906 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2907 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2908 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002909}
2910
2911void InputDispatcher::addPointerWindowTargetLocked(
2912 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002913 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2914 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2915 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002916 if (pointerIds.none()) {
2917 for (const auto& target : inputTargets) {
2918 LOG(INFO) << "Target: " << target;
2919 }
2920 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2921 return;
2922 }
2923 std::vector<InputTarget>::iterator it =
2924 std::find_if(inputTargets.begin(), inputTargets.end(),
2925 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002926 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002927 });
2928
2929 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2930 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2931 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2932 // input targets for hovering pointers and for touching pointers.
2933 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2934 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002935 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002936 // Force the code below to create a new input target
2937 it = inputTargets.end();
2938 }
2939
2940 const WindowInfo* windowInfo = windowHandle->getInfo();
2941
2942 if (it == inputTargets.end()) {
2943 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002944 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2945 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002946 if (!target) {
2947 return;
2948 }
2949 inputTargets.push_back(*target);
2950 it = inputTargets.end() - 1;
2951 }
2952
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002953 if (it->dispatchMode != dispatchMode) {
2954 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2955 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2956 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002957 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002958 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2959 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002960 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002961 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002962 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002963 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2964 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002965
chaviw1ff3d1e2020-07-01 15:53:47 -07002966 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967}
2968
Michael Wright3dd60e22019-03-27 22:06:44 +00002969void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002970 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002971 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2972 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002973
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002974 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2975 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002976 target.connection = monitor.connection;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002977 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2978 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002979 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2980 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002981 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002982 target.setDefaultPointerTransform(target.displayTransform);
2983 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985}
2986
Robert Carrc9bf1d32020-04-13 17:21:08 -07002987/**
2988 * Indicate whether one window handle should be considered as obscuring
2989 * another window handle. We only check a few preconditions. Actually
2990 * checking the bounds is left to the caller.
2991 */
chaviw98318de2021-05-19 16:45:23 -05002992static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2993 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002994 // Compare by token so cloned layers aren't counted
2995 if (haveSameToken(windowHandle, otherHandle)) {
2996 return false;
2997 }
2998 auto info = windowHandle->getInfo();
2999 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003000 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003001 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003002 } else if (otherInfo->alpha == 0 &&
3003 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003004 // Those act as if they were invisible, so we don't need to flag them.
3005 // We do want to potentially flag touchable windows even if they have 0
3006 // opacity, since they can consume touches and alter the effects of the
3007 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003008 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003009 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3010 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003011 } else if (info->ownerUid == otherInfo->ownerUid) {
3012 // If ownerUid is the same we don't generate occlusion events as there
3013 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003014 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003015 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003016 return false;
3017 } else if (otherInfo->displayId != info->displayId) {
3018 return false;
3019 }
3020 return true;
3021}
3022
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003023/**
3024 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3025 * untrusted, one should check:
3026 *
3027 * 1. If result.hasBlockingOcclusion is true.
3028 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3029 * BLOCK_UNTRUSTED.
3030 *
3031 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3032 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3033 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3034 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3035 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3036 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3037 *
3038 * If neither of those is true, then it means the touch can be allowed.
3039 */
3040InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003041 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3042 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003043 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003044 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 TouchOcclusionInfo info;
3046 info.hasBlockingOcclusion = false;
3047 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003048 info.obscuringUid = gui::Uid::INVALID;
3049 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003050 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003051 if (windowHandle == otherHandle) {
3052 break; // All future windows are below us. Exit early.
3053 }
chaviw98318de2021-05-19 16:45:23 -05003054 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003055 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3056 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003057 if (DEBUG_TOUCH_OCCLUSION) {
3058 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003059 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003060 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3062 // we perform the checks below to see if the touch can be propagated or not based on the
3063 // window's touch occlusion mode
3064 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3065 info.hasBlockingOcclusion = true;
3066 info.obscuringUid = otherInfo->ownerUid;
3067 info.obscuringPackage = otherInfo->packageName;
3068 break;
3069 }
3070 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003071 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003072 float opacity =
3073 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3074 // Given windows A and B:
3075 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3076 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3077 opacityByUid[uid] = opacity;
3078 if (opacity > info.obscuringOpacity) {
3079 info.obscuringOpacity = opacity;
3080 info.obscuringUid = uid;
3081 info.obscuringPackage = otherInfo->packageName;
3082 }
3083 }
3084 }
3085 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003086 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003087 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003088 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003089 return info;
3090}
3091
chaviw98318de2021-05-19 16:45:23 -05003092std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003093 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003094 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003095 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3096 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3097 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003098 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003099 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003100 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3101 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003102 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3103 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3104 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003105 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003106}
3107
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003108bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3109 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003110 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3111 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003112 return false;
3113 }
3114 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003115 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003116 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003117 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003118 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3119 return false;
3120 }
3121 return true;
3122}
3123
chaviw98318de2021-05-19 16:45:23 -05003124bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003127 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3128 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003129 if (windowHandle == otherHandle) {
3130 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 }
chaviw98318de2021-05-19 16:45:23 -05003132 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003133 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003134 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 return true;
3136 }
3137 }
3138 return false;
3139}
3140
chaviw98318de2021-05-19 16:45:23 -05003141bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003142 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003143 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3144 const WindowInfo* windowInfo = windowHandle->getInfo();
3145 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003146 if (windowHandle == otherHandle) {
3147 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003148 }
chaviw98318de2021-05-19 16:45:23 -05003149 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003150 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003151 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003152 return true;
3153 }
3154 }
3155 return false;
3156}
3157
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003158std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003159 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 if (applicationHandle != nullptr) {
3161 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003162 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 } else {
3164 return applicationHandle->getName();
3165 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003166 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003167 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
3171}
3172
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003173void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003174 if (!isUserActivityEvent(eventEntry)) {
3175 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003176 return;
3177 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003178
3179 const int32_t eventType = getUserActivityEventType(eventEntry);
3180 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3181 // Note that we're directly getting the time diff between the current event and the previous
3182 // event. This is assuming that the first user event always happens at a timestamp that is
3183 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3184 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3185 // value than the potential first user activity event time, so this is ok.
3186 std::chrono::nanoseconds timeSinceLastEvent =
3187 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3188 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3189 return;
3190 }
3191 }
3192
Tiger Huang721e26f2018-07-24 22:26:19 +08003193 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003194 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003195 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003196 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003197 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003198 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003199 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 }
3201 }
3202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003203 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003204 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003205 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3206 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 return;
3208 }
Josep del Riob3981622023-04-18 15:49:45 +00003209 if (windowDisablingUserActivityInfo != nullptr) {
3210 if (DEBUG_DISPATCH_CYCLE) {
3211 ALOGD("Not poking user activity: disabled by window '%s'.",
3212 windowDisablingUserActivityInfo->name.c_str());
3213 }
3214 return;
3215 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003218 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003219 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3220 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 return;
3222 }
Josep del Riob3981622023-04-18 15:49:45 +00003223 // If the key code is unknown, we don't consider it user activity
3224 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3225 return;
3226 }
3227 // Don't inhibit events that were intercepted or are not passed to
3228 // the apps, like system shortcuts
3229 if (windowDisablingUserActivityInfo != nullptr &&
3230 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3231 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3232 if (DEBUG_DISPATCH_CYCLE) {
3233 ALOGD("Not poking user activity: disabled by window '%s'.",
3234 windowDisablingUserActivityInfo->name.c_str());
3235 }
3236 return;
3237 }
3238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003241 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003242 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003243 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003244 break;
3245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003248 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003249 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3250 REQUIRES(mLock) {
3251 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003252 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003253 };
3254 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255}
3256
3257void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003258 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003259 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003260 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003261 ATRACE_NAME_IF(ATRACE_ENABLED(),
3262 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3263 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003264 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003265 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003266 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003268 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003269 inputTarget.getPointerInfoString().c_str());
3270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // Skip this event if the connection status is not normal.
3273 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003274 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003275 if (DEBUG_DISPATCH_CYCLE) {
3276 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003277 connection->getInputChannelName().c_str(),
3278 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 return;
3281 }
3282
3283 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003286 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003287 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003289 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003290 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003291 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3292 logDispatchStateLocked();
3293 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3294 "target on connection "
3295 << connection->getInputChannelName() << " for "
3296 << originalMotionEntry.getDescription();
3297 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003298 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003299 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3300 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 if (!splitMotionEntry) {
3302 return; // split event was dropped
3303 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003304 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3305 std::string reason = std::string("reason=pointer cancel on split window");
3306 android_log_event_list(LOGTAG_INPUT_CANCEL)
3307 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3308 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003309 if (DEBUG_FOCUS) {
3310 ALOGD("channel '%s' ~ Split motion event.",
3311 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003312 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003313 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003314 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3315 std::move(splitMotionEntry),
3316 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 return;
3318 }
3319 }
3320
3321 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003322 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3323 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324}
3325
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003326void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3327 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3328 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003329 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003330 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3331 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003332 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003333
hongzuo liu95785e22022-09-06 02:51:35 +00003334 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003336 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337
3338 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003339 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 startDispatchCycleLocked(currentTime, connection);
3341 }
3342}
3343
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003344void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003345 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003346 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003347 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3348 eventEntry->type == EventEntry::Type::MOTION;
3349 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3350 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3351 << inputTarget << " connection: " << connection->getInputChannelName()
3352 << " entry: " << eventEntry->getDescription();
3353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 // This is a new event.
3355 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003356 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003357 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003359 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3360 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003361 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003363 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003364 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003365 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3366 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003367 LOG(WARNING) << "channel " << connection->getInputChannelName()
3368 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 return; // skip the inconsistent event
3370 }
3371 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003374 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003375 std::shared_ptr<const MotionEntry> resolvedMotion =
3376 std::static_pointer_cast<const MotionEntry>(eventEntry);
3377 {
3378 // Determine the resolved motion entry.
3379 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3380 int32_t resolvedAction = motionEntry.action;
3381 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003383 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003384 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003385 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003386 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003387 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003388 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003389 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003390 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003391 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003392 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3393 }
3394 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3395 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3396 motionEntry.displayId)) {
3397 if (DEBUG_DISPATCH_CYCLE) {
3398 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3399 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3400 "enter event";
3401 }
3402 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3403 }
3404
3405 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3406 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3407 }
3408 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3409 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3410 }
3411 if (dispatchEntry->targetFlags.test(
3412 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3413 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3414 }
3415
3416 dispatchEntry->resolvedFlags = resolvedFlags;
3417 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003418 std::optional<std::vector<PointerProperties>> usingProperties;
3419 std::optional<std::vector<PointerCoords>> usingCoords;
3420 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3421 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3422 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3423 // the dispatcher, and therefore the coordinates of this event are currently
3424 // incorrect. These events should use the coordinates of the last dispatched
3425 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3426 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3427 std::optional<std::pair<std::vector<PointerProperties>,
3428 std::vector<PointerCoords>>>
3429 pointerInfo =
3430 connection->inputState.getPointersOfLastEvent(motionEntry,
3431 hovering);
3432 if (pointerInfo) {
3433 usingProperties = pointerInfo->first;
3434 usingCoords = pointerInfo->second;
3435 }
3436 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003437 // Generate a new MotionEntry with a new eventId using the resolved action and
3438 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003439 resolvedMotion = std::make_shared<
3440 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3441 motionEntry.eventTime, motionEntry.deviceId,
3442 motionEntry.source, motionEntry.displayId,
3443 motionEntry.policyFlags, resolvedAction,
3444 motionEntry.actionButton, resolvedFlags,
3445 motionEntry.metaState, motionEntry.buttonState,
3446 motionEntry.classification, motionEntry.edgeFlags,
3447 motionEntry.xPrecision, motionEntry.yPrecision,
3448 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3449 motionEntry.downTime,
3450 usingProperties.value_or(motionEntry.pointerProperties),
3451 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003452 if (ATRACE_ENABLED()) {
3453 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3454 ") to MotionEvent(id=0x%" PRIx32 ").",
3455 motionEntry.id, resolvedMotion->id);
3456 ATRACE_NAME(message.c_str());
3457 }
3458
3459 // Set the resolved motion entry in the DispatchEntry.
3460 dispatchEntry->eventEntry = resolvedMotion;
3461 eventEntry = resolvedMotion;
3462 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003465 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3466 // devices being active at the same time in the same window, so if a new device is
3467 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003468 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003469 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003470 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003471 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003472 << connection->getInputChannelName() << " with event "
3473 << cancelEvent->getDescription();
3474 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3475 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003476 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003477
3478 // Send these cancel events to the queue before sending the event from the new
3479 // device.
3480 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3481 }
3482
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003483 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003484 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003485 LOG(WARNING) << "channel " << connection->getInputChannelName()
3486 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487 return; // skip the inconsistent event
3488 }
3489
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003490 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3491 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003492 // Skip reporting pointer down outside focus to the policy.
3493 break;
3494 }
3495
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003496 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003497 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498
3499 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003501 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003502 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003503 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3504 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003505 break;
3506 }
Chris Yef59a2f42020-10-16 12:55:26 -07003507 case EventEntry::Type::SENSOR: {
3508 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3509 break;
3510 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003511 case EventEntry::Type::CONFIGURATION_CHANGED:
3512 case EventEntry::Type::DEVICE_RESET: {
3513 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003514 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003515 break;
3516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518
3519 // Remember that we are waiting for this dispatch to complete.
3520 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003521 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523
3524 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003525 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003526 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003527}
3528
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003529/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003530 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003531 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003532 * The first role is to log input interaction with windows, which helps determine what the user was
3533 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3534 * that user started interacting with launcher window, as well as any other window that received
3535 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3536 * when the set of tokens that received the event changes. It is not logged again as long as the
3537 * user is interacting with the same windows.
3538 *
3539 * The second role is to track input device activity for metrics collection. For each input event,
3540 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3541 * input_interaction logs, the device interaction is reported even when the set of interaction
3542 * tokens do not change.
3543 *
3544 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3545 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003546 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003547void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3548 const std::vector<InputTarget>& targets) {
3549 int32_t deviceId;
3550 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 // Skip ACTION_UP events, and all events other than keys and motions
3552 if (entry.type == EventEntry::Type::KEY) {
3553 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3554 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3555 return;
3556 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003557 deviceId = keyEntry.deviceId;
3558 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003559 } else if (entry.type == EventEntry::Type::MOTION) {
3560 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3561 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003562 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3563 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003564 return;
3565 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003566 deviceId = motionEntry.deviceId;
3567 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003568 } else {
3569 return; // Not a key or a motion
3570 }
3571
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003572 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003573 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003574 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003575 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003576 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003577 continue; // Skip windows that receive ACTION_OUTSIDE
3578 }
3579
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003580 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003582 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003583 if (target.windowHandle) {
3584 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3585 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003586 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003587
3588 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3589 REQUIRES(mLock) {
3590 scoped_unlock unlock(mLock);
3591 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3592 };
3593 postCommandLocked(std::move(command));
3594
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003595 if (newConnectionTokens == mInteractionConnectionTokens) {
3596 return; // no change
3597 }
3598 mInteractionConnectionTokens = newConnectionTokens;
3599
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003600 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003601 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003602 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003603 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003604 std::string message = "Interaction with: " + targetList;
3605 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003606 message += "<none>";
3607 }
3608 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3609}
3610
chaviwfd6d3512019-03-25 13:23:49 -07003611void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003612 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003613 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003614 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3615 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003616 return;
3617 }
3618
Vishnu Nairc519ff72021-01-21 08:23:08 -08003619 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003620 if (focusedToken == token) {
3621 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003622 return;
3623 }
3624
Prabir Pradhancef936d2021-07-21 16:17:52 +00003625 auto command = [this, token]() REQUIRES(mLock) {
3626 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003627 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003628 };
3629 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630}
3631
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003632status_t InputDispatcher::publishMotionEvent(Connection& connection,
3633 DispatchEntry& dispatchEntry) const {
3634 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3635 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3636
3637 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003638 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003639
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003640 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003641 // Set the X and Y offset and X and Y scale depending on the input source.
3642 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003643 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003644 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3645 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003646 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003647 scaledCoords[i] = motionEntry.pointerCoords[i];
3648 // Don't apply window scale here since we don't want scale to affect raw
3649 // coordinates. The scale will be sent back to the client and applied
3650 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003651 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003652 }
3653 usingCoords = scaledCoords;
3654 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003655 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003656 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003657 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003658 scaledCoords[i].clear();
3659 }
3660 usingCoords = scaledCoords;
3661 }
3662
3663 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3664
3665 // Publish the motion event.
3666 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003667 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3668 motionEntry.source, motionEntry.displayId, std::move(hmac),
3669 motionEntry.action, motionEntry.actionButton,
3670 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3671 motionEntry.metaState, motionEntry.buttonState,
3672 motionEntry.classification, dispatchEntry.transform,
3673 motionEntry.xPrecision, motionEntry.yPrecision,
3674 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3675 dispatchEntry.rawTransform, motionEntry.downTime,
3676 motionEntry.eventTime, motionEntry.getPointerCount(),
3677 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003678}
3679
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003681 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003682 ATRACE_NAME_IF(ATRACE_ENABLED(),
3683 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3684 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003685 if (DEBUG_DISPATCH_CYCLE) {
3686 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003689 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003690 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003692 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003693 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694
3695 // Publish the event.
3696 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003697 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3698 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003699 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003700 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3701 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003702 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003703 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3704 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003708 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003709 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3710 keyEntry.deviceId, keyEntry.source,
3711 keyEntry.displayId, std::move(hmac),
3712 keyEntry.action, dispatchEntry->resolvedFlags,
3713 keyEntry.keyCode, keyEntry.scanCode,
3714 keyEntry.metaState, keyEntry.repeatCount,
3715 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003716 if (mTracer) {
3717 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3718 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 }
3721
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003722 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003723 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003724 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3725 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003726 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003727 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003728 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003729 if (mTracer) {
3730 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3731 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 break;
3733 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003734
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003735 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003736 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003737 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003738 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003739 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003740 break;
3741 }
3742
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003743 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3744 const TouchModeEntry& touchModeEntry =
3745 static_cast<const TouchModeEntry&>(eventEntry);
3746 status = connection->inputPublisher
3747 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3748 touchModeEntry.inTouchMode);
3749
3750 break;
3751 }
3752
Prabir Pradhan99987712020-11-10 18:43:05 -08003753 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3754 const auto& captureEntry =
3755 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3756 status = connection->inputPublisher
3757 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003758 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003759 break;
3760 }
3761
arthurhungb89ccb02020-12-30 16:19:01 +08003762 case EventEntry::Type::DRAG: {
3763 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3764 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3765 dragEntry.id, dragEntry.x,
3766 dragEntry.y,
3767 dragEntry.isExiting);
3768 break;
3769 }
3770
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003771 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003772 case EventEntry::Type::DEVICE_RESET:
3773 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003774 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003775 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 }
3779
3780 // Check the result.
3781 if (status) {
3782 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003783 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 "This is unexpected because the wait queue is empty, so the pipe "
3786 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003787 "event to it, status=%s(%d)",
3788 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3789 status);
Harry Cutts33476232023-01-30 19:57:29 +00003790 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 } else {
3792 // Pipe is full and we are waiting for the app to finish process some events
3793 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003794 if (DEBUG_DISPATCH_CYCLE) {
3795 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3796 "waiting for the application to catch up",
3797 connection->getInputChannelName().c_str());
3798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 }
3800 } else {
3801 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003802 "status=%s(%d)",
3803 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3804 status);
Harry Cutts33476232023-01-30 19:57:29 +00003805 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807 return;
3808 }
3809
3810 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003811 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3812 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3813 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003814 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003815 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003816 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003817 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003818 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820}
3821
chaviw09c8d2d2020-08-24 15:48:26 -07003822std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3823 size_t size;
3824 switch (event.type) {
3825 case VerifiedInputEvent::Type::KEY: {
3826 size = sizeof(VerifiedKeyEvent);
3827 break;
3828 }
3829 case VerifiedInputEvent::Type::MOTION: {
3830 size = sizeof(VerifiedMotionEvent);
3831 break;
3832 }
3833 }
3834 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3835 return mHmacKeyManager.sign(start, size);
3836}
3837
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003838const std::array<uint8_t, 32> InputDispatcher::getSignature(
3839 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003840 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003841 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003842 // Only sign events up and down events as the purely move events
3843 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003844 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003845 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003846
3847 VerifiedMotionEvent verifiedEvent =
3848 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3849 verifiedEvent.actionMasked = actionMasked;
3850 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3851 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003852}
3853
3854const std::array<uint8_t, 32> InputDispatcher::getSignature(
3855 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3856 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3857 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003858 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003859}
3860
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003862 const std::shared_ptr<Connection>& connection,
3863 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 if (DEBUG_DISPATCH_CYCLE) {
3865 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3866 connection->getInputChannelName().c_str(), seq, toString(handled));
3867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003869 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 return;
3871 }
3872
3873 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003874 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3875 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3876 };
3877 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878}
3879
3880void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003881 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003883 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003884 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3885 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
3888 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003889 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003890 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003891 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003892 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893
3894 // The connection appears to be unrecoverably broken.
3895 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003896 if (connection->status == Connection::Status::NORMAL) {
3897 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
3899 if (notify) {
3900 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003901 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3902 connection->getInputChannelName().c_str());
3903
3904 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003905 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003906 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003907 };
3908 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 }
3910 }
3911}
3912
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003913void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003914 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003915 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003916 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918}
3919
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003920void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003922 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924}
3925
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003926int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3927 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003928 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003929 if (connection == nullptr) {
3930 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3931 connectionToken.get(), events);
3932 return 0; // remove the callback
3933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003935 bool notify;
3936 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3937 if (!(events & ALOOPER_EVENT_INPUT)) {
3938 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3939 "events=0x%x",
3940 connection->getInputChannelName().c_str(), events);
3941 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 }
3943
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003944 nsecs_t currentTime = now();
3945 bool gotOne = false;
3946 status_t status = OK;
3947 for (;;) {
3948 Result<InputPublisher::ConsumerResponse> result =
3949 connection->inputPublisher.receiveConsumerResponse();
3950 if (!result.ok()) {
3951 status = result.error().code();
3952 break;
3953 }
3954
3955 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3956 const InputPublisher::Finished& finish =
3957 std::get<InputPublisher::Finished>(*result);
3958 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3959 finish.consumeTime);
3960 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003961 if (shouldReportMetricsForConnection(*connection)) {
3962 const InputPublisher::Timeline& timeline =
3963 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003964 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3965 connection->getToken(),
3966 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003967 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003968 }
3969 gotOne = true;
3970 }
3971 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003972 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003973 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 return 1;
3975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 }
3977
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003978 notify = status != DEAD_OBJECT || !connection->monitor;
3979 if (notify) {
3980 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3981 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3982 status);
3983 }
3984 } else {
3985 // Monitor channels are never explicitly unregistered.
3986 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003987 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003988 notify = !connection->monitor && stillHaveWindowHandle;
3989 if (notify) {
3990 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3991 connection->getInputChannelName().c_str(), events);
3992 }
3993 }
3994
3995 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003996 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003997 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998}
3999
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004000void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004002 // Cancel windows (i.e. non-monitors).
4003 // A channel must have at least one window to receive any input. If a window was removed, the
4004 // event streams directed to the window will already have been canceled during window removal.
4005 // So there is no need to generate cancellations for connections without any windows.
4006 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4007 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4008 // through a non-touched window if there are more than one window for an input channel.
4009 if (cancelPointers) {
4010 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4011 if (options.displayId.has_value() && options.displayId != displayId) {
4012 continue;
4013 }
4014 for (const auto& touchedWindow : touchState.windows) {
4015 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4016 }
4017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004019 // Follow up by generating cancellations for all windows, because we don't explicitly track
4020 // the windows that have an ongoing focus event stream.
4021 if (cancelNonPointers) {
4022 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4023 for (const auto& windowHandle : handles) {
4024 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4025 }
4026 }
4027 }
4028
4029 // Cancel monitors.
4030 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031}
4032
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004033void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004034 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004035 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004036 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004037 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4038 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004039 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004040 }
4041}
4042
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004043void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4044 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4045 const std::shared_ptr<Connection>& connection) {
4046 if (windowHandle == nullptr) {
4047 LOG(FATAL) << __func__ << ": Window handle must not be null";
4048 }
4049 if (connection) {
4050 // The connection can be optionally provided to avoid multiple lookups.
4051 if (windowHandle->getToken() != connection->getToken()) {
4052 LOG(FATAL) << __func__
4053 << ": Wrong connection provided for window: " << windowHandle->getName();
4054 }
4055 }
4056
4057 std::shared_ptr<Connection> resolvedConnection =
4058 connection ? connection : getConnectionLocked(windowHandle->getToken());
4059 if (!resolvedConnection) {
4060 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4061 return;
4062 }
4063 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4064}
4065
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004067 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4068 const sp<WindowInfoHandle>& window) {
4069 if (!connection->monitor && window == nullptr) {
4070 LOG(FATAL) << __func__
4071 << ": Cannot send event to non-monitor channel without a window - channel: "
4072 << connection->getInputChannelName();
4073 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004074 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 return;
4076 }
4077
4078 nsecs_t currentTime = now();
4079
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004080 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004081 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004083 if (cancelationEvents.empty()) {
4084 return;
4085 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004086
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004087 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4088 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004089 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004090 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004091 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004092 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004093
Arthur Hungb3307ee2021-10-14 10:57:37 +00004094 std::string reason = std::string("reason=").append(options.reason);
4095 android_log_event_list(LOGTAG_INPUT_CANCEL)
4096 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4097
hongzuo liu95785e22022-09-06 02:51:35 +00004098 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004099 // The target to use if we don't find a window associated with the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004100 const InputTarget fallbackTarget{.connection = connection};
4101 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004102
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004103 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004104 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004105 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004106
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004107 switch (cancelationEventEntry->type) {
4108 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004109 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004110 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004111 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4112 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004113 } else {
4114 targets.emplace_back(fallbackTarget);
4115 }
4116 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004117 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004119 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004120 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004121 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004122 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004123 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004124 pointerIndex++) {
4125 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4126 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004127 if (mDragState && mDragState->dragWindow->getToken() == token &&
4128 pointerIds.test(mDragState->pointerId)) {
4129 LOG(INFO) << __func__
4130 << ": Canceling drag and drop because the pointers for the drag "
4131 "window are being canceled.";
4132 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4133 mDragState.reset();
4134 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004135 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4136 ftl::Flags<InputTarget::Flags>(), pointerIds,
4137 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004138 } else {
4139 targets.emplace_back(fallbackTarget);
4140 const auto it = mDisplayInfos.find(motionEntry.displayId);
4141 if (it != mDisplayInfos.end()) {
4142 targets.back().displayTransform = it->second.transform;
4143 targets.back().setDefaultPointerTransform(it->second.transform);
4144 }
4145 }
4146 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004149 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004150 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004151 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4152 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004153 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004154 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004155 break;
4156 }
4157 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004158 case EventEntry::Type::DEVICE_RESET:
4159 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004160 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004161 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004162 break;
4163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 }
4165
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004166 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004167 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004169
hongzuo liu95785e22022-09-06 02:51:35 +00004170 // If the outbound queue was previously empty, start the dispatch cycle going.
4171 if (wasEmpty && !connection->outboundQueue.empty()) {
4172 startDispatchCycleLocked(currentTime, connection);
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174}
4175
Svet Ganov5d3bc372020-01-26 23:11:07 -08004176void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004177 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004178 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004179 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004180 return;
4181 }
4182
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004183 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004184 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004185
4186 if (downEvents.empty()) {
4187 return;
4188 }
4189
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004190 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004191 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4192 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004193 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004194
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004195 const auto [_, touchedWindowState, displayId] =
4196 findTouchStateWindowAndDisplayLocked(connection->getToken());
4197 if (touchedWindowState == nullptr) {
4198 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4199 }
4200 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201
hongzuo liu95785e22022-09-06 02:51:35 +00004202 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004203 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004204 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205 switch (downEventEntry->type) {
4206 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004207 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4208 if (windowHandle != nullptr) {
4209 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004210 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004211 pointerIndex++) {
4212 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4213 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004214 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4215 targetFlags, pointerIds, motionEntry.downTime,
4216 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004217 } else {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004218 targets.emplace_back(
4219 InputTarget{.connection = connection, .flags = targetFlags});
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004220 const auto it = mDisplayInfos.find(motionEntry.displayId);
4221 if (it != mDisplayInfos.end()) {
4222 targets.back().displayTransform = it->second.transform;
4223 targets.back().setDefaultPointerTransform(it->second.transform);
4224 }
4225 }
4226 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004227 break;
4228 }
4229
4230 case EventEntry::Type::KEY:
4231 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004232 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004234 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004235 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004236 case EventEntry::Type::SENSOR:
4237 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004239 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004240 break;
4241 }
4242 }
4243
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004244 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004245 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 }
4247
hongzuo liu95785e22022-09-06 02:51:35 +00004248 // If the outbound queue was previously empty, start the dispatch cycle going.
4249 if (wasEmpty && !connection->outboundQueue.empty()) {
4250 startDispatchCycleLocked(downTime, connection);
4251 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004252}
4253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004255 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4256 nsecs_t splitDownTime) {
4257 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258
4259 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004260 std::vector<PointerProperties> splitPointerProperties;
4261 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004263 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 uint32_t splitPointerCount = 0;
4265
4266 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004269 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004271 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004273 splitPointerProperties.push_back(pointerProperties);
4274 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 splitPointerCount += 1;
4276 }
4277 }
4278
4279 if (splitPointerCount != pointerIds.count()) {
4280 // This is bad. We are missing some of the pointers that we expected to deliver.
4281 // Most likely this indicates that we received an ACTION_MOVE events that has
4282 // different pointer ids than we expected based on the previous ACTION_DOWN
4283 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4284 // in this way.
4285 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004286 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004287 "a broken sequence of pointer ids from the input device: %s",
4288 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004289 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004292 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4295 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004296 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004298 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004300 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 if (pointerIds.count() == 1) {
4302 // The first/last pointer went down/up.
4303 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004305 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4306 ? AMOTION_EVENT_ACTION_CANCEL
4307 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 } else {
4309 // A secondary pointer went down/up.
4310 uint32_t splitPointerIndex = 0;
4311 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4312 splitPointerIndex += 1;
4313 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 action = maskedAction |
4315 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
4317 } else {
4318 // An unrelated pointer changed.
4319 action = AMOTION_EVENT_ACTION_MOVE;
4320 }
4321 }
4322
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004323 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4324 logDispatchStateLocked();
4325 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4326 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4327 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004328 }
4329
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004330 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004331 ATRACE_NAME_IF(ATRACE_ENABLED(),
4332 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4333 ").",
4334 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004336 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4337 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004338 originalMotionEntry.deviceId, originalMotionEntry.source,
4339 originalMotionEntry.displayId,
4340 originalMotionEntry.policyFlags, action,
4341 originalMotionEntry.actionButton,
4342 originalMotionEntry.flags, originalMotionEntry.metaState,
4343 originalMotionEntry.buttonState,
4344 originalMotionEntry.classification,
4345 originalMotionEntry.edgeFlags,
4346 originalMotionEntry.xPrecision,
4347 originalMotionEntry.yPrecision,
4348 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004349 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004350 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 return splitMotionEntry;
4353}
4354
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004355void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4356 std::scoped_lock _l(mLock);
4357 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4358}
4359
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004360void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004361 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004362 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364
Antonio Kantekf16f2832021-09-28 04:39:20 +00004365 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004367 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004369 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004370 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004371 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 } // release lock
4373
4374 if (needWake) {
4375 mLooper->wake();
4376 }
4377}
4378
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004380 ALOGD_IF(debugInboundEventDetails(),
4381 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4382 ", deviceId=%d, source=%s, displayId=%" PRId32
4383 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4384 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004385 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4386 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4387 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004388 Result<void> keyCheck = validateKeyEvent(args.action);
4389 if (!keyCheck.ok()) {
4390 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 return;
4392 }
4393
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004394 uint32_t policyFlags = args.policyFlags;
4395 int32_t flags = args.flags;
4396 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004397 // InputDispatcher tracks and generates key repeats on behalf of
4398 // whatever notifies it, so repeatCount should always be set to 0
4399 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4401 policyFlags |= POLICY_FLAG_VIRTUAL;
4402 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 if (policyFlags & POLICY_FLAG_FUNCTION) {
4405 metaState |= AMETA_FUNCTION_ON;
4406 }
4407
4408 policyFlags |= POLICY_FLAG_TRUSTED;
4409
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004410 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004412 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4413 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4414 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415
Michael Wright2b3c3302018-03-02 17:19:13 +00004416 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004417 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004418 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4419 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422
Antonio Kantekf16f2832021-09-28 04:39:20 +00004423 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 { // acquire lock
4425 mLock.lock();
4426
4427 if (shouldSendKeyToInputFilterLocked(args)) {
4428 mLock.unlock();
4429
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004430 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004431 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 return; // event was consumed by the filter
4433 }
4434
4435 mLock.lock();
4436 }
4437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004438 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004439 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4440 args.deviceId, args.source, args.displayId, policyFlags,
4441 args.action, flags, keyCode, args.scanCode, metaState,
4442 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004443 if (mTracer) {
4444 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 mLock.unlock();
4449 } // release lock
4450
4451 if (needWake) {
4452 mLooper->wake();
4453 }
4454}
4455
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004456bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 return mInputFilterEnabled;
4458}
4459
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004460void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004461 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004462 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004463 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004464 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4466 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004467 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4468 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4469 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4470 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4471 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004472 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004473 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4474 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004475 i, args.pointerProperties[i].id,
4476 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4477 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4478 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4479 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4480 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4481 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4482 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4483 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4484 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4485 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004488
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004489 Result<void> motionCheck =
4490 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4491 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004492 if (!motionCheck.ok()) {
4493 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4494 return;
4495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004497 if (DEBUG_VERIFY_EVENTS) {
4498 auto [it, _] =
4499 mVerifiersByDisplay.try_emplace(args.displayId,
4500 StringPrintf("display %" PRId32, args.displayId));
4501 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004502 it->second.processMovement(args.deviceId, args.source, args.action,
4503 args.getPointerCount(), args.pointerProperties.data(),
4504 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004505 if (!result.ok()) {
4506 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4507 }
4508 }
4509
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004510 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004512
4513 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004514 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4515 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004516 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4517 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004518 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520
Antonio Kantekf16f2832021-09-28 04:39:20 +00004521 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 { // acquire lock
4523 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004524 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4525 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4526 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004527 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004528 if (touchStateIt != mTouchStatesByDisplay.end()) {
4529 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004530 if (touchState.hasTouchingPointers(args.deviceId) ||
4531 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004532 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4533 }
4534 }
4535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
4537 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004538 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004539 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004540 displayTransform = it->second.transform;
4541 }
4542
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 mLock.unlock();
4544
4545 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004546 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4547 args.action, args.actionButton, args.flags, args.edgeFlags,
4548 args.metaState, args.buttonState, args.classification,
4549 displayTransform, args.xPrecision, args.yPrecision,
4550 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004551 args.downTime, args.eventTime, args.getPointerCount(),
4552 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
4554 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004555 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 return; // event was consumed by the filter
4557 }
4558
4559 mLock.lock();
4560 }
4561
4562 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004563 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004564 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4565 args.deviceId, args.source, args.displayId,
4566 policyFlags, args.action, args.actionButton,
4567 args.flags, args.metaState, args.buttonState,
4568 args.classification, args.edgeFlags, args.xPrecision,
4569 args.yPrecision, args.xCursorPosition,
4570 args.yCursorPosition, args.downTime,
4571 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004572 if (mTracer) {
4573 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4577 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004578 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004579 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004580 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4581 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4582 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004583 }
4584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004585 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 mLock.unlock();
4587 } // release lock
4588
4589 if (needWake) {
4590 mLooper->wake();
4591 }
4592}
4593
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004594void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004595 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004596 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4597 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004598 args.id, args.eventTime, args.deviceId, args.source,
4599 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004600 }
Chris Yef59a2f42020-10-16 12:55:26 -07004601
Antonio Kantekf16f2832021-09-28 04:39:20 +00004602 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004603 { // acquire lock
4604 mLock.lock();
4605
4606 // Just enqueue a new sensor event.
4607 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004608 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4609 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4610 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004611
4612 needWake = enqueueInboundEventLocked(std::move(newEntry));
4613 mLock.unlock();
4614 } // release lock
4615
4616 if (needWake) {
4617 mLooper->wake();
4618 }
4619}
4620
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004621void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004622 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004623 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4624 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004625 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004626 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004627}
4628
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004629bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004630 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631}
4632
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004633void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004634 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004635 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4636 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004637 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004640 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004642 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643}
4644
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004645void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004646 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004647 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4648 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650
Antonio Kantekf16f2832021-09-28 04:39:20 +00004651 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004653 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004655 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004657 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004658
4659 for (auto& [_, verifier] : mVerifiersByDisplay) {
4660 verifier.resetDevice(args.deviceId);
4661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 } // release lock
4663
4664 if (needWake) {
4665 mLooper->wake();
4666 }
4667}
4668
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004669void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004670 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004671 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4672 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004673 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004674
Antonio Kantekf16f2832021-09-28 04:39:20 +00004675 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004676 { // acquire lock
4677 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004678 auto entry =
4679 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004680 needWake = enqueueInboundEventLocked(std::move(entry));
4681 } // release lock
4682
4683 if (needWake) {
4684 mLooper->wake();
4685 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004686}
4687
Prabir Pradhan5735a322022-04-11 17:23:34 +00004688InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004689 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004690 InputEventInjectionSync syncMode,
4691 std::chrono::milliseconds timeout,
4692 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004693 Result<void> eventValidation = validateInputEvent(*event);
4694 if (!eventValidation.ok()) {
4695 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4696 return InputEventInjectionResult::FAILED;
4697 }
4698
Prabir Pradhan65613802023-02-22 23:36:58 +00004699 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004700 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4701 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4702 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4703 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004704 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004705 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
Prabir Pradhan5735a322022-04-11 17:23:34 +00004707 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004709 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004710 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4711 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4712 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4713 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4714 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004715 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004716 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004717 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004718 }
4719
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004720 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4721 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4722
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004723 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004725 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004726 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004727 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004728 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004729 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4730 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4731 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004732 int32_t keyCode = incomingKey.getKeyCode();
4733 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004734 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004735 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004736 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4737 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4738 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004740 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4741 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004742 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743
4744 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4745 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004746 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004747 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4748 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4749 std::to_string(t.duration().count()).c_str());
4750 }
4751 }
4752
4753 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004754 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004755 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4756 incomingKey.getEventTime(), resolvedDeviceId,
4757 incomingKey.getSource(), incomingKey.getDisplayId(),
4758 policyFlags, action, flags, keyCode,
4759 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004760 incomingKey.getRepeatCount(),
4761 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004762 if (mTracer) {
4763 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4764 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004765 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004766 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 }
4768
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004769 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004770 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004771 const bool isPointerEvent =
4772 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4773 // If a pointer event has no displayId specified, inject it to the default display.
4774 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4775 ? ADISPLAY_ID_DEFAULT
4776 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004777 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004778
4779 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004780 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004782 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4783 motionEvent.getAction(), eventTime,
4784 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4786 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4787 std::to_string(t.duration().count()).c_str());
4788 }
4789 }
4790
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004791 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4792 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4793 }
4794
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004796 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004797 const size_t pointerCount = motionEvent.getPointerCount();
4798 const std::vector<PointerProperties>
4799 pointerProperties(motionEvent.getPointerProperties(),
4800 motionEvent.getPointerProperties() + pointerCount);
4801
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004802 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004804 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4805 *sampleEventTimes, resolvedDeviceId,
4806 motionEvent.getSource(), displayId, policyFlags,
4807 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004808 motionEvent.getActionButton(), flags,
4809 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004810 motionEvent.getButtonState(),
4811 motionEvent.getClassification(),
4812 motionEvent.getEdgeFlags(),
4813 motionEvent.getXPrecision(),
4814 motionEvent.getYPrecision(),
4815 motionEvent.getRawXCursorPosition(),
4816 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004817 motionEvent.getDownTime(), pointerProperties,
4818 std::vector<PointerCoords>(samplePointerCoords,
4819 samplePointerCoords +
4820 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004821 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004822 if (mTracer) {
4823 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4824 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004825 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004826 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004828 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004829 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004830 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4831 resolvedDeviceId, motionEvent.getSource(), displayId,
4832 policyFlags, motionEvent.getAction(),
4833 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004834 motionEvent.getMetaState(), motionEvent.getButtonState(),
4835 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4836 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4837 motionEvent.getRawXCursorPosition(),
4838 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4839 pointerProperties,
4840 std::vector<PointerCoords>(samplePointerCoords,
4841 samplePointerCoords +
4842 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004843 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4844 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004845 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004846 }
4847 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004850 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004851 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
4854
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004856 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004857 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004858 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004859 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004860 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004861 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
4864 mLock.unlock();
4865
4866 if (needWake) {
4867 mLooper->wake();
4868 }
4869
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004870 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004872 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004874 if (syncMode == InputEventInjectionSync::NONE) {
4875 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 } else {
4877 for (;;) {
4878 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004879 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 break;
4881 }
4882
4883 nsecs_t remainingTimeout = endTime - now();
4884 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004885 if (DEBUG_INJECTION) {
4886 ALOGD("injectInputEvent - Timed out waiting for injection result "
4887 "to become available.");
4888 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004889 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 break;
4891 }
4892
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004893 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004896 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4897 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004899 if (DEBUG_INJECTION) {
4900 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4901 injectionState->pendingForegroundDispatches);
4902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 nsecs_t remainingTimeout = endTime - now();
4904 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004905 if (DEBUG_INJECTION) {
4906 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4907 "dispatches to finish.");
4908 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004909 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 break;
4911 }
4912
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004913 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 }
4915 }
4916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 } // release lock
4918
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004919 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004920 LOG(INFO) << "injectInputEvent - Finished with result "
4921 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
4924 return injectionResult;
4925}
4926
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004927std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004928 std::array<uint8_t, 32> calculatedHmac;
4929 std::unique_ptr<VerifiedInputEvent> result;
4930 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004931 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004932 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4933 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4934 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004935 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004936 break;
4937 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004938 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004939 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4940 VerifiedMotionEvent verifiedMotionEvent =
4941 verifiedMotionEventFromMotionEvent(motionEvent);
4942 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004943 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004944 break;
4945 }
4946 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004947 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004948 return nullptr;
4949 }
4950 }
4951 if (calculatedHmac == INVALID_HMAC) {
4952 return nullptr;
4953 }
tyiu1573a672023-02-21 22:38:32 +00004954 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004955 return nullptr;
4956 }
4957 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004958}
4959
Prabir Pradhan24047542023-11-02 17:14:59 +00004960void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004961 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004962 if (!entry.injectionState) {
4963 // Not an injected event.
4964 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004966
4967 InjectionState& injectionState = *entry.injectionState;
4968 if (DEBUG_INJECTION) {
4969 LOG(INFO) << "Setting input event injection result to "
4970 << ftl::enum_string(injectionResult);
4971 }
4972
4973 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4974 // Log the outcome since the injector did not wait for the injection result.
4975 switch (injectionResult) {
4976 case InputEventInjectionResult::SUCCEEDED:
4977 ALOGV("Asynchronous input event injection succeeded.");
4978 break;
4979 case InputEventInjectionResult::TARGET_MISMATCH:
4980 ALOGV("Asynchronous input event injection target mismatch.");
4981 break;
4982 case InputEventInjectionResult::FAILED:
4983 ALOGW("Asynchronous input event injection failed.");
4984 break;
4985 case InputEventInjectionResult::TIMED_OUT:
4986 ALOGW("Asynchronous input event injection timed out.");
4987 break;
4988 case InputEventInjectionResult::PENDING:
4989 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4990 break;
4991 }
4992 }
4993
4994 injectionState.injectionResult = injectionResult;
4995 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996}
4997
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004998void InputDispatcher::transformMotionEntryForInjectionLocked(
4999 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005000 // Input injection works in the logical display coordinate space, but the input pipeline works
5001 // display space, so we need to transform the injected events accordingly.
5002 const auto it = mDisplayInfos.find(entry.displayId);
5003 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005004 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005005
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005006 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5007 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5008 const vec2 cursor =
5009 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5010 {entry.xCursorPosition, entry.yCursorPosition});
5011 entry.xCursorPosition = cursor.x;
5012 entry.yCursorPosition = cursor.y;
5013 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005014 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005015 entry.pointerCoords[i] =
5016 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5017 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005018 }
5019}
5020
Prabir Pradhan24047542023-11-02 17:14:59 +00005021void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005022 if (entry.injectionState) {
5023 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 }
5025}
5026
Prabir Pradhan24047542023-11-02 17:14:59 +00005027void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005028 if (entry.injectionState) {
5029 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005031 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005032 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 }
5034 }
5035}
5036
chaviw98318de2021-05-19 16:45:23 -05005037const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005038 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005039 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005040 auto it = mWindowHandlesByDisplay.find(displayId);
5041 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005042}
5043
chaviw98318de2021-05-19 16:45:23 -05005044sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005045 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005046 if (windowHandleToken == nullptr) {
5047 return nullptr;
5048 }
5049
Prabir Pradhan16463382023-10-12 23:03:19 +00005050 if (!displayId) {
5051 // Look through all displays.
5052 for (auto& it : mWindowHandlesByDisplay) {
5053 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5054 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5055 if (windowHandle->getToken() == windowHandleToken) {
5056 return windowHandle;
5057 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005060 return nullptr;
5061 }
5062
Prabir Pradhan16463382023-10-12 23:03:19 +00005063 // Only look through the requested display.
5064 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005065 if (windowHandle->getToken() == windowHandleToken) {
5066 return windowHandle;
5067 }
5068 }
5069 return nullptr;
5070}
5071
chaviw98318de2021-05-19 16:45:23 -05005072sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5073 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005074 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005075 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5076 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005077 if (handle->getId() == windowHandle->getId() &&
5078 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005079 if (windowHandle->getInfo()->displayId != it.first) {
5080 ALOGE("Found window %s in display %" PRId32
5081 ", but it should belong to display %" PRId32,
5082 windowHandle->getName().c_str(), it.first,
5083 windowHandle->getInfo()->displayId);
5084 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005085 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005089 return nullptr;
5090}
5091
chaviw98318de2021-05-19 16:45:23 -05005092sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005093 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5094 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095}
5096
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005097ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5098 auto displayInfoIt = mDisplayInfos.find(displayId);
5099 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5100 : kIdentityTransform;
5101}
5102
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005103bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5104 const MotionEntry& motionEntry) const {
5105 const WindowInfo& info = *window->getInfo();
5106
5107 // Skip spy window targets that are not valid for targeted injection.
5108 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005109 return false;
5110 }
5111
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005112 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5113 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5114 return false;
5115 }
5116
5117 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5118 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5119 window->getName().c_str());
5120 return false;
5121 }
5122
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005123 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005124 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005125 ALOGW("Not sending touch to %s because there's no corresponding connection",
5126 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005127 return false;
5128 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005129
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005131 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005132 return false;
5133 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005134
5135 // Drop events that can't be trusted due to occlusion
5136 const auto [x, y] = resolveTouchedPosition(motionEntry);
5137 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5138 if (!isTouchTrustedLocked(occlusionInfo)) {
5139 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005140 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005141 for (const auto& log : occlusionInfo.debugInfo) {
5142 ALOGD("%s", log.c_str());
5143 }
5144 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005145 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5146 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005147 return false;
5148 }
5149
5150 // Drop touch events if requested by input feature
5151 if (shouldDropInput(motionEntry, window)) {
5152 return false;
5153 }
5154
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005155 // Ignore touches if stylus is down anywhere on screen
5156 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5157 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5158 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5159 return false;
5160 }
5161
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005162 return true;
5163}
5164
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005165void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005166 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5167 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005168 // Remove all handles on a display if there are no windows left.
5169 mWindowHandlesByDisplay.erase(displayId);
5170 return;
5171 }
5172
5173 // Since we compare the pointer of input window handles across window updates, we need
5174 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005175 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5176 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5177 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005178 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005179 }
5180
chaviw98318de2021-05-19 16:45:23 -05005181 std::vector<sp<WindowInfoHandle>> newHandles;
5182 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005183 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005184 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005185 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005186 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005187 const bool canReceiveInput =
5188 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5189 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005190 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005191 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005192 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005193 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005194 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005195 }
5196
5197 if (info->displayId != displayId) {
5198 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5199 handle->getName().c_str(), displayId, info->displayId);
5200 continue;
5201 }
5202
Robert Carredd13602020-04-13 17:24:34 -07005203 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5204 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005205 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005206 oldHandle->updateFrom(handle);
5207 newHandles.push_back(oldHandle);
5208 } else {
5209 newHandles.push_back(handle);
5210 }
5211 }
5212
5213 // Insert or replace
5214 mWindowHandlesByDisplay[displayId] = newHandles;
5215}
5216
Arthur Hungb92218b2018-08-14 12:00:21 +08005217/**
5218 * Called from InputManagerService, update window handle list by displayId that can receive input.
5219 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5220 * If set an empty list, remove all handles from the specific display.
5221 * For focused handle, check if need to change and send a cancel event to previous one.
5222 * For removed handle, check if need to send a cancel event if already in touch.
5223 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005224void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005225 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005226 if (DEBUG_FOCUS) {
5227 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005228 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005229 windowList += iwh->getName() + " ";
5230 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005231 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233
Prabir Pradhand65552b2021-10-07 11:23:50 -07005234 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005235 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005236 const WindowInfo& info = *window->getInfo();
5237
5238 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005239 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005240 if (noInputWindow && window->getToken() != nullptr) {
5241 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5242 window->getName().c_str());
5243 window->releaseChannel();
5244 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005245
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005246 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005247 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5248 !info.inputConfig.test(
5249 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005250 "%s has feature SPY, but is not a trusted overlay.",
5251 window->getName().c_str());
5252
Prabir Pradhand65552b2021-10-07 11:23:50 -07005253 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005254 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5255 !info.inputConfig.test(
5256 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005257 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5258 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005259 }
5260
Arthur Hung72d8dc32020-03-28 00:48:39 +00005261 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005262 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005263 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264
chaviw98318de2021-05-19 16:45:23 -05005265 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005266
chaviw98318de2021-05-19 16:45:23 -05005267 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005268
Vishnu Nairc519ff72021-01-21 08:23:08 -08005269 std::optional<FocusResolver::FocusChanges> changes =
5270 mFocusResolver.setInputWindows(displayId, windowHandles);
5271 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005272 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005275 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5276 mTouchStatesByDisplay.find(displayId);
5277 if (stateIt != mTouchStatesByDisplay.end()) {
5278 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005279 for (size_t i = 0; i < state.windows.size();) {
5280 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005281 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005282 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5283 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005284 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5285 "touched window was removed");
5286 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5287 // Since we are about to drop the touch, cancel the events for the wallpaper as
5288 // well.
5289 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5290 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5291 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5292 if (const auto& ww = state.getWallpaperWindow(); ww) {
5293 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005296 state.windows.erase(state.windows.begin() + i);
5297 } else {
5298 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 }
5300 }
arthurhungb89ccb02020-12-30 16:19:01 +08005301
arthurhung6d4bed92021-03-17 11:59:33 +08005302 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005303 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005304 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005305 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005306 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005307 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5308 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005309 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005310 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005311 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005312
Arthur Hung72d8dc32020-03-28 00:48:39 +00005313 // Release information for windows that are no longer present.
5314 // This ensures that unused input channels are released promptly.
5315 // Otherwise, they might stick around until the window handle is destroyed
5316 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005317 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005318 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005319 if (DEBUG_FOCUS) {
5320 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005321 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005322 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005323 }
chaviw291d88a2019-02-14 10:33:58 -08005324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325}
5326
5327void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005328 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005329 if (DEBUG_FOCUS) {
5330 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5331 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5332 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005333 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005334 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005335 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 } // release lock
5337
5338 // Wake up poll loop since it may need to make new input dispatching choices.
5339 mLooper->wake();
5340}
5341
Vishnu Nair599f1412021-06-21 10:39:58 -07005342void InputDispatcher::setFocusedApplicationLocked(
5343 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5344 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5345 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5346
5347 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5348 return; // This application is already focused. No need to wake up or change anything.
5349 }
5350
5351 // Set the new application handle.
5352 if (inputApplicationHandle != nullptr) {
5353 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5354 } else {
5355 mFocusedApplicationHandlesByDisplay.erase(displayId);
5356 }
5357
5358 // No matter what the old focused application was, stop waiting on it because it is
5359 // no longer focused.
5360 resetNoFocusedWindowTimeoutLocked();
5361}
5362
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005363void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5364 if (interval.count() < 0) {
5365 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5366 }
5367 std::scoped_lock _l(mLock);
5368 mMinTimeBetweenUserActivityPokes = interval;
5369}
5370
Tiger Huang721e26f2018-07-24 22:26:19 +08005371/**
5372 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5373 * the display not specified.
5374 *
5375 * We track any unreleased events for each window. If a window loses the ability to receive the
5376 * released event, we will send a cancel event to it. So when the focused display is changed, we
5377 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5378 * display. The display-specified events won't be affected.
5379 */
5380void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005381 if (DEBUG_FOCUS) {
5382 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5383 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005384 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005385 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005386
5387 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005388 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005389 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005390 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005391 const auto windowHandle =
5392 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5393 if (windowHandle == nullptr) {
5394 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005395 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005396 CancelationOptions
5397 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5398 "The display which contains this window no longer has focus.");
5399 options.displayId = ADISPLAY_ID_NONE;
5400 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 }
5402 mFocusedDisplayId = displayId;
5403
Chris Ye3c2d6f52020-08-09 10:39:48 -07005404 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005405 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005406 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005407
Vishnu Nairad321cd2020-08-20 16:40:21 -07005408 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005409 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005410 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005411 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005412 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005413 }
5414 }
5415 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005416 } // release lock
5417
5418 // Wake up poll loop since it may need to make new input dispatching choices.
5419 mLooper->wake();
5420}
5421
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005423 if (DEBUG_FOCUS) {
5424 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426
5427 bool changed;
5428 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005429 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430
5431 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5432 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005433 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 }
5435
5436 if (mDispatchEnabled && !enabled) {
5437 resetAndDropEverythingLocked("dispatcher is being disabled");
5438 }
5439
5440 mDispatchEnabled = enabled;
5441 mDispatchFrozen = frozen;
5442 changed = true;
5443 } else {
5444 changed = false;
5445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 } // release lock
5447
5448 if (changed) {
5449 // Wake up poll loop since it may need to make new input dispatching choices.
5450 mLooper->wake();
5451 }
5452}
5453
5454void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005455 if (DEBUG_FOCUS) {
5456 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
5459 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005460 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
5462 if (mInputFilterEnabled == enabled) {
5463 return;
5464 }
5465
5466 mInputFilterEnabled = enabled;
5467 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5468 } // release lock
5469
5470 // Wake up poll loop since there might be work to do to drop everything.
5471 mLooper->wake();
5472}
5473
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005474bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005475 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005476 bool needWake = false;
5477 {
5478 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005479 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005480 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005481 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005482 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5483 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005484 mTouchModePerDisplay.count(displayId) == 0
5485 ? "not set"
5486 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5487
Antonio Kantek15beb512022-06-13 22:35:41 +00005488 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5489 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005490 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005491 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005492 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005493 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5494 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005495 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005496 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005497 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005498 return false;
5499 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005500 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005501 mTouchModePerDisplay[displayId] = inTouchMode;
5502 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5503 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005504 needWake = enqueueInboundEventLocked(std::move(entry));
5505 } // release lock
5506
5507 if (needWake) {
5508 mLooper->wake();
5509 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005510 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005511}
5512
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005513bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005514 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5515 if (focusedToken == nullptr) {
5516 return false;
5517 }
5518 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5519 return isWindowOwnedBy(windowHandle, pid, uid);
5520}
5521
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005522bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005523 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5524 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5525 const sp<WindowInfoHandle> windowHandle =
5526 getWindowHandleLocked(connectionToken);
5527 return isWindowOwnedBy(windowHandle, pid, uid);
5528 }) != mInteractionConnectionTokens.end();
5529}
5530
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005531void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5532 if (opacity < 0 || opacity > 1) {
5533 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5534 return;
5535 }
5536
5537 std::scoped_lock lock(mLock);
5538 mMaximumObscuringOpacityForTouch = opacity;
5539}
5540
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005541std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5542InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005543 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5544 for (TouchedWindow& w : state.windows) {
5545 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005546 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005547 }
5548 }
5549 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005550 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005551}
5552
arthurhungb89ccb02020-12-30 16:19:01 +08005553bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5554 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005555 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005556 if (DEBUG_FOCUS) {
5557 ALOGD("Trivial transfer to same window.");
5558 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005559 return true;
5560 }
5561
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005563 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564
Arthur Hungabbb9d82021-09-01 14:52:30 +00005565 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005566 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005567
Arthur Hungabbb9d82021-09-01 14:52:30 +00005568 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005569 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 return false;
5571 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005572 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5573 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005574 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5575 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005576 return false;
5577 }
5578 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005579
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005580 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5581 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5582 if (!toWindowHandle) {
5583 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005584 return false;
5585 }
5586
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005587 if (DEBUG_FOCUS) {
5588 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005589 touchedWindow->windowHandle->getName().c_str(),
5590 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 }
5592
Arthur Hungabbb9d82021-09-01 14:52:30 +00005593 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005594 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005595 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005596 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005599 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005600 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005601 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005602 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005603 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005604 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005605 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005606 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Arthur Hungabbb9d82021-09-01 14:52:30 +00005608 // Store the dragging window.
5609 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005610 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005611 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5612 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005613 return false;
5614 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005615 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005616 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005617 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 }
5619
Arthur Hungabbb9d82021-09-01 14:52:30 +00005620 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005621 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5622 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005623 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005624 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005625 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5626 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005627 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005628 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5629 newTargetFlags);
5630
5631 // Check if the wallpaper window should deliver the corresponding event.
5632 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005633 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 } // release lock
5636
5637 // Wake up poll loop since it may need to make new input dispatching choices.
5638 mLooper->wake();
5639 return true;
5640}
5641
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005642/**
5643 * Get the touched foreground window on the given display.
5644 * Return null if there are no windows touched on that display, or if more than one foreground
5645 * window is being touched.
5646 */
5647sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5648 auto stateIt = mTouchStatesByDisplay.find(displayId);
5649 if (stateIt == mTouchStatesByDisplay.end()) {
5650 ALOGI("No touch state on display %" PRId32, displayId);
5651 return nullptr;
5652 }
5653
5654 const TouchState& state = stateIt->second;
5655 sp<WindowInfoHandle> touchedForegroundWindow;
5656 // If multiple foreground windows are touched, return nullptr
5657 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005658 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005659 if (touchedForegroundWindow != nullptr) {
5660 ALOGI("Two or more foreground windows: %s and %s",
5661 touchedForegroundWindow->getName().c_str(),
5662 window.windowHandle->getName().c_str());
5663 return nullptr;
5664 }
5665 touchedForegroundWindow = window.windowHandle;
5666 }
5667 }
5668 return touchedForegroundWindow;
5669}
5670
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005671// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005672bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005673 sp<IBinder> fromToken;
5674 { // acquire lock
5675 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005676 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005677 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005678 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5679 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005680 return false;
5681 }
5682
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005683 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5684 if (from == nullptr) {
5685 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5686 return false;
5687 }
5688
5689 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005690 } // release lock
5691
5692 return transferTouchFocus(fromToken, destChannelToken);
5693}
5694
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005696 if (DEBUG_FOCUS) {
5697 ALOGD("Resetting and dropping all events (%s).", reason);
5698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699
Michael Wrightfb04fd52022-11-24 22:31:11 +00005700 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 synthesizeCancelationEventsForAllConnectionsLocked(options);
5702
5703 resetKeyRepeatLocked();
5704 releasePendingEventLocked();
5705 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005706 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005708 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005709 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710}
5711
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005712void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 dumpDispatchStateLocked(dump);
5715
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005716 std::istringstream stream(dump);
5717 std::string line;
5718
5719 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005720 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 }
5722}
5723
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005724std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005725 std::string dump;
5726
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005727 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5728 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005729
5730 std::string windowName = "None";
5731 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005732 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005733 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5734 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5735 : "token has capture without window";
5736 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005737 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005738
5739 return dump;
5740}
5741
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005742void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005743 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5744 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5745 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005746 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747
Tiger Huang721e26f2018-07-24 22:26:19 +08005748 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5749 dump += StringPrintf(INDENT "FocusedApplications:\n");
5750 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5751 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005752 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005753 const std::chrono::duration timeout =
5754 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005755 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005756 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005757 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005760 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005762
Vishnu Nairc519ff72021-01-21 08:23:08 -08005763 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005764 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005766 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005767 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005768 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005769 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5770 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005773 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 }
5775
arthurhung6d4bed92021-03-17 11:59:33 +08005776 if (mDragState) {
5777 dump += StringPrintf(INDENT "DragState:\n");
5778 mDragState->dump(dump, INDENT2);
5779 }
5780
Arthur Hungb92218b2018-08-14 12:00:21 +08005781 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005782 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5783 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5784 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5785 const auto& displayInfo = it->second;
5786 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5787 displayInfo.logicalHeight);
5788 displayInfo.transform.dump(dump, "transform", INDENT4);
5789 } else {
5790 dump += INDENT2 "No DisplayInfo found!\n";
5791 }
5792
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005793 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005794 dump += INDENT2 "Windows:\n";
5795 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005796 dump += StringPrintf(INDENT3 "%zu: %s", i,
5797 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005798 }
5799 } else {
5800 dump += INDENT2 "Windows: <none>\n";
5801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
5803 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005804 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005807 if (!mGlobalMonitorsByDisplay.empty()) {
5808 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5809 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005810 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005813 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005816 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817
5818 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005819 if (!mRecentQueue.empty()) {
5820 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005821 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005822 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005823 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005824 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 }
5826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829
5830 // Dump event currently being dispatched.
5831 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005832 dump += INDENT "PendingEvent:\n";
5833 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005834 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005835 dump += StringPrintf(", age=%" PRId64 "ms\n",
5836 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005838 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 }
5840
5841 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005842 if (!mInboundQueue.empty()) {
5843 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005844 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005845 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005846 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005847 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848 }
5849 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005850 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 }
5852
Prabir Pradhancef936d2021-07-21 16:17:52 +00005853 if (!mCommandQueue.empty()) {
5854 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5855 } else {
5856 dump += INDENT "CommandQueue: <empty>\n";
5857 }
5858
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005859 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005860 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005861 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005862 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005863 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005864 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005865 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005866 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005867 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005869 if (!connection->outboundQueue.empty()) {
5870 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5871 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005872 dump += dumpQueue(connection->outboundQueue, currentTime);
5873
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005875 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876 }
5877
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005878 if (!connection->waitQueue.empty()) {
5879 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5880 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005881 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005883 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005885 std::string inputStateDump = streamableToString(connection->inputState);
5886 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005887 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005888 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 }
5891 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005892 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 }
5894
Antonio Kantek15beb512022-06-13 22:35:41 +00005895 if (!mTouchModePerDisplay.empty()) {
5896 dump += INDENT "TouchModePerDisplay:\n";
5897 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5898 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5899 std::to_string(touchMode).c_str());
5900 }
5901 } else {
5902 dump += INDENT "TouchModePerDisplay: <none>\n";
5903 }
5904
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005905 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005906 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5907 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5908 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005909 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005910 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005911 dump += INDENT "InputTracer: ";
5912 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913}
5914
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005915void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005916 const size_t numMonitors = monitors.size();
5917 for (size_t i = 0; i < numMonitors; i++) {
5918 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005919 const std::shared_ptr<Connection>& connection = monitor.connection;
5920 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005921 dump += "\n";
5922 }
5923}
5924
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005925class LooperEventCallback : public LooperCallback {
5926public:
5927 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5928 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5929
5930private:
5931 std::function<int(int events)> mCallback;
5932};
5933
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005934Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005935 if (DEBUG_CHANNEL_CREATION) {
5936 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005939 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005940 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005941 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005942
5943 if (result) {
5944 return base::Error(result) << "Failed to open input channel pair with name " << name;
5945 }
5946
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005948 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005949 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005950 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005951 std::shared_ptr<Connection> connection =
5952 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5953 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005955 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5956 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005957 ALOGE("Created a new connection, but the token %p is already known", token.get());
5958 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005959
5960 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5961 this, std::placeholders::_1, token);
5962
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005963 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005964 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 } // release lock
5966
5967 // Wake the looper because some connections have changed.
5968 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005969 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970}
5971
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005972Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005973 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005974 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005975 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005976 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005977 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005978 if (result) {
5979 return base::Error(result) << "Failed to open input channel pair with name " << name;
5980 }
5981
Michael Wright3dd60e22019-03-27 22:06:44 +00005982 { // acquire lock
5983 std::scoped_lock _l(mLock);
5984
5985 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005986 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5987 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005988 }
5989
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005990 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005991 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005992 std::shared_ptr<Connection> connection =
5993 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5994 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005995
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005996 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5997 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005998 ALOGE("Created a new connection, but the token %p is already known", token.get());
5999 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006000
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006001 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6002 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006003
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006004 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006005
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006006 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006007 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006008 }
Garfield Tan15601662020-09-22 15:32:38 -07006009
Michael Wright3dd60e22019-03-27 22:06:44 +00006010 // Wake the looper because some connections have changed.
6011 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006012 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006013}
6014
Garfield Tan15601662020-09-22 15:32:38 -07006015status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006017 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018
Harry Cutts33476232023-01-30 19:57:29 +00006019 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 if (status) {
6021 return status;
6022 }
6023 } // release lock
6024
6025 // Wake the poll loop because removing the connection may have changed the current
6026 // synchronization state.
6027 mLooper->wake();
6028 return OK;
6029}
6030
Garfield Tan15601662020-09-22 15:32:38 -07006031status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6032 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006033 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006034 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006035 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036 return BAD_VALUE;
6037 }
6038
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006039 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006040
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006042 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043 }
6044
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006045 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046
6047 nsecs_t currentTime = now();
6048 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6049
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006050 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 return OK;
6052}
6053
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006054void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006055 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6056 auto& [displayId, monitors] = *it;
6057 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006058 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006059 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006060
Michael Wright3dd60e22019-03-27 22:06:44 +00006061 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006062 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006063 } else {
6064 ++it;
6065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 }
6067}
6068
Michael Wright3dd60e22019-03-27 22:06:44 +00006069status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006071 return pilferPointersLocked(token);
6072}
Michael Wright3dd60e22019-03-27 22:06:44 +00006073
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006074status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006075 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6076 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006077 LOG(WARNING)
6078 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006079 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006080 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006081
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006082 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006083 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006084 LOG(WARNING)
6085 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6086 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006087 return BAD_VALUE;
6088 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006089 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006090 if (deviceIds.empty()) {
6091 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006092 return BAD_VALUE;
6093 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006094
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006095 for (const DeviceId deviceId : deviceIds) {
6096 TouchState& state = *statePtr;
6097 TouchedWindow& window = *windowPtr;
6098 // Send cancel events to all the input channels we're stealing from.
6099 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6100 "input channel stole pointer stream");
6101 options.deviceId = deviceId;
6102 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006103 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6104 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006105 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006106
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006107 std::string canceledWindows;
6108 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006109 if (w.windowHandle->getToken() != token) {
6110 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006111 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006112 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006113 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006114 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006115 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006116 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006117 << " is stealing input gesture for device " << deviceId << " from "
6118 << canceledWindows;
6119
6120 // Prevent the gesture from being sent to any other windows.
6121 // This only blocks relevant pointers to be sent to other windows
6122 window.addPilferingPointers(deviceId, pointerIds);
6123
6124 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006125 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006126 return OK;
6127}
6128
Prabir Pradhan99987712020-11-10 18:43:05 -08006129void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6130 { // acquire lock
6131 std::scoped_lock _l(mLock);
6132 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006133 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006134 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6135 windowHandle != nullptr ? windowHandle->getName().c_str()
6136 : "token without window");
6137 }
6138
Vishnu Nairc519ff72021-01-21 08:23:08 -08006139 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006140 if (focusedToken != windowToken) {
6141 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6142 enabled ? "enable" : "disable");
6143 return;
6144 }
6145
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006146 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006147 ALOGW("Ignoring request to %s Pointer Capture: "
6148 "window has %s requested pointer capture.",
6149 enabled ? "enable" : "disable", enabled ? "already" : "not");
6150 return;
6151 }
6152
Christine Franksb768bb42021-11-29 12:11:31 -08006153 if (enabled) {
6154 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6155 mIneligibleDisplaysForPointerCapture.end(),
6156 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6157 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6158 return;
6159 }
6160 }
6161
Prabir Pradhan99987712020-11-10 18:43:05 -08006162 setPointerCaptureLocked(enabled);
6163 } // release lock
6164
6165 // Wake the thread to process command entries.
6166 mLooper->wake();
6167}
6168
Christine Franksb768bb42021-11-29 12:11:31 -08006169void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6170 { // acquire lock
6171 std::scoped_lock _l(mLock);
6172 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6173 if (!isEligible) {
6174 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6175 }
6176 } // release lock
6177}
6178
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006179std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006180 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006181 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006182 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006183 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006184 }
6185 }
6186 }
6187 return std::nullopt;
6188}
6189
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006190std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6191 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006192 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006193 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006194 }
6195
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006196 for (const auto& [token, connection] : mConnectionsByToken) {
6197 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006198 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006199 }
6200 }
Robert Carr4e670e52018-08-15 13:26:12 -07006201
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006202 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203}
6204
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006205std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006206 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006207 if (connection == nullptr) {
6208 return "<nullptr>";
6209 }
6210 return connection->getInputChannelName();
6211}
6212
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006213void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006214 mAnrTracker.eraseToken(connection->getToken());
6215 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006216}
6217
Prabir Pradhancef936d2021-07-21 16:17:52 +00006218void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006219 const std::shared_ptr<Connection>& connection,
6220 uint32_t seq, bool handled,
6221 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006222 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006223 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006224
6225 { // Start critical section
6226 auto dispatchEntryIt =
6227 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6228 [seq](auto& e) { return e->seq == seq; });
6229 if (dispatchEntryIt == connection->waitQueue.end()) {
6230 return;
6231 }
6232
6233 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6234
6235 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6236 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006237 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006238 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6239 }
6240 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006241 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006242 dispatchEntry.deliveryTime, consumeTime, finishTime);
6243 }
6244
6245 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006246 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6247 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006248 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006249 }
6250 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006251
6252 // Dequeue the event and start the next cycle.
6253 // Because the lock might have been released, it is possible that the
6254 // contents of the wait queue to have been drained, so we need to double-check
6255 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006256 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6257 [seq](auto& e) { return e->seq == seq; });
6258 if (entryIt != connection->waitQueue.end()) {
6259 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6260 connection->waitQueue.erase(entryIt);
6261
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006262 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006263 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6264 if (!connection->responsive) {
6265 connection->responsive = isConnectionResponsive(*connection);
6266 if (connection->responsive) {
6267 // The connection was unresponsive, and now it's responsive.
6268 processConnectionResponsiveLocked(*connection);
6269 }
6270 }
6271 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006272 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006273 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6274 // Only dispatch fallbacks if there is a window for the connection.
6275 if (windowHandle != nullptr) {
6276 const auto inputTarget =
6277 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6278 dispatchEntry->targetFlags,
6279 fallbackKeyEntry->downTime);
6280 if (inputTarget.has_value()) {
6281 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6282 *inputTarget);
6283 }
6284 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006285 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006286 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287 }
6288
6289 // Start the next dispatch cycle for this connection.
6290 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291}
6292
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6294 const sp<IBinder>& newToken) {
6295 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6296 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006297 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 };
6299 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300}
6301
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6303 auto command = [this, token, x, y]() REQUIRES(mLock) {
6304 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006305 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006306 };
6307 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006308}
6309
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006310void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311 if (connection == nullptr) {
6312 LOG_ALWAYS_FATAL("Caller must check for nullness");
6313 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6315 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006316 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006317 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006318 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006319 return;
6320 }
6321 /**
6322 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6323 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6324 * has changed. This could cause newer entries to time out before the already dispatched
6325 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6326 * processes the events linearly. So providing information about the oldest entry seems to be
6327 * most useful.
6328 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006329 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6330 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006331 std::string reason =
6332 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006333 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006334 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006335 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006336 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006337 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006338
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006339 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6340
6341 // Stop waking up for events on this connection, it is already unresponsive
6342 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006343}
6344
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006345void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6346 std::string reason =
6347 StringPrintf("%s does not have a focused window", application->getName().c_str());
6348 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006349
Yabin Cui8eb9c552023-06-08 18:05:07 +00006350 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006351 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006352 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006353 };
6354 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006355}
6356
chaviw98318de2021-05-19 16:45:23 -05006357void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006358 const std::string& reason) {
6359 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6360 updateLastAnrStateLocked(windowLabel, reason);
6361}
6362
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006363void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6364 const std::string& reason) {
6365 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006366 updateLastAnrStateLocked(windowLabel, reason);
6367}
6368
6369void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6370 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006372 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 struct tm tm;
6374 localtime_r(&t, &tm);
6375 char timestr[64];
6376 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006377 mLastAnrState.clear();
6378 mLastAnrState += INDENT "ANR:\n";
6379 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006380 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6381 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006382 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383}
6384
Prabir Pradhancef936d2021-07-21 16:17:52 +00006385void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006386 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006387 const KeyEvent event = createKeyEvent(entry);
6388 nsecs_t delay = 0;
6389 { // release lock
6390 scoped_unlock unlock(mLock);
6391 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006392 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006393 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6394 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6395 std::to_string(t.duration().count()).c_str());
6396 }
6397 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398
6399 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006400 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006401 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006402 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006404 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006405 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407}
6408
Prabir Pradhancef936d2021-07-21 16:17:52 +00006409void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006410 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006411 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006412 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006413 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006414 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006415 };
6416 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006417}
6418
Prabir Pradhanedd96402022-02-15 01:46:16 -08006419void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006420 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006421 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006422 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006423 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006424 };
6425 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006426}
6427
6428/**
6429 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6430 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6431 * command entry to the command queue.
6432 */
6433void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6434 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006435 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006436 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006437 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006438 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006439 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006440 pid = findMonitorPidByTokenLocked(connectionToken);
6441 } else {
6442 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006443 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006444 reason.c_str());
6445 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6446 if (handle != nullptr) {
6447 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006449 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006450 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006451}
6452
6453/**
6454 * Tell the policy that a connection has become responsive so that it can stop ANR.
6455 */
6456void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006457 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006458 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006459 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006460 pid = findMonitorPidByTokenLocked(connectionToken);
6461 } else {
6462 // The connection is a window
6463 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6464 if (handle != nullptr) {
6465 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006466 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006467 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006468 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006469}
6470
Prabir Pradhan24047542023-11-02 17:14:59 +00006471std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006472 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006473 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006474 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006475 if (!handled) {
6476 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006477 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006478 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006479 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006481
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 // Get the fallback key state.
6483 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006484 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006485 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 connection->inputState.removeFallbackKey(originalKeyCode);
6488 }
6489
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006490 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 // If the application handles the original key for which we previously
6492 // generated a fallback or if the window is not a foreground window,
6493 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006495 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006496 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6497 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6498 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6499 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6500 keyEntry.policyFlags);
6501 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006502 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504
6505 mLock.unlock();
6506
Prabir Pradhana41d2442023-04-20 21:30:40 +00006507 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006508 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6509 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006510 unhandledKeyFallback) {
6511 event = *unhandledKeyFallback;
6512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513
6514 mLock.lock();
6515
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006516 // Cancel the fallback key, but only if we still have a window for the channel.
6517 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006518 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006519 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6520 if (windowHandle != nullptr) {
6521 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6522 "application handled the original non-fallback key "
6523 "or is no longer a foreground target, "
6524 "canceling previously dispatched fallback key");
6525 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006526 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006529 connection->inputState.removeFallbackKey(originalKeyCode);
6530 }
6531 } else {
6532 // If the application did not handle a non-fallback key, first check
6533 // that we are in a good state to perform unhandled key event processing
6534 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006535 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006536 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006537 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6538 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6539 "since this is not an initial down. "
6540 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6541 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6542 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006543 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006546 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006547 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6548 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6549 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6550 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6551 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006552 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006553
6554 mLock.unlock();
6555
Prabir Pradhana41d2442023-04-20 21:30:40 +00006556 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006557 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6558 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006559 fb) {
6560 fallback = true;
6561 event = *fb;
6562 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006563
6564 mLock.lock();
6565
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006566 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006567 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006568 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006569 }
6570
6571 // Latch the fallback keycode for this key on an initial down.
6572 // The fallback keycode cannot change at any other point in the lifecycle.
6573 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006574 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006575 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006576 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006577 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006578 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006579 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006580 }
6581
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006582 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583
6584 // Cancel the fallback key if the policy decides not to send it anymore.
6585 // We will continue to dispatch the key to the policy but we will no
6586 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006587 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6588 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006589 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6590 if (fallback) {
6591 ALOGD("Unhandled key event: Policy requested to send key %d"
6592 "as a fallback for %d, but on the DOWN it had requested "
6593 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006594 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006595 } else {
6596 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6597 "but on the DOWN it had requested to send %d. "
6598 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006599 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006600 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006601 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006602
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006603 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6604 if (windowHandle != nullptr) {
6605 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6606 "canceling fallback, policy no longer desires it");
6607 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006608 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006609 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610
6611 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006612 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006613 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006614 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006615 }
6616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6619 {
6620 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006621 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006622 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006623 for (const auto& [key, value] : fallbackKeys) {
6624 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006625 }
6626 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6627 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006629 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006630
6631 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006632 // Return the fallback key that we want dispatched to the channel.
6633 std::unique_ptr<KeyEntry> newEntry =
6634 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6635 event.getEventTime(), event.getDeviceId(),
6636 event.getSource(), event.getDisplayId(),
6637 keyEntry.policyFlags, keyEntry.action,
6638 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6639 *fallbackKeyCode, event.getScanCode(),
6640 event.getMetaState(), event.getRepeatCount(),
6641 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006642 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6643 ALOGD("Unhandled key event: Dispatching fallback key. "
6644 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006645 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006646 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006647 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006648 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006649 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6650 ALOGD("Unhandled key event: No fallback key.");
6651 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006652
6653 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006654 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006655 }
6656 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006657 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658}
6659
Michael Wrightd02c5b62014-02-10 15:10:22 -08006660void InputDispatcher::traceInboundQueueLengthLocked() {
6661 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006662 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663 }
6664}
6665
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006666void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006667 if (ATRACE_ENABLED()) {
6668 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006669 snprintf(counterName, sizeof(counterName), "oq:%s",
6670 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006671 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 }
6673}
6674
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006675void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006676 if (ATRACE_ENABLED()) {
6677 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006678 snprintf(counterName, sizeof(counterName), "wq:%s",
6679 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006680 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681 }
6682}
6683
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006684void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006685 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006686
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006687 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688 dumpDispatchStateLocked(dump);
6689
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006690 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006691 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006692 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 }
6694}
6695
6696void InputDispatcher::monitor() {
6697 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006698 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006700 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006701}
6702
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006703/**
6704 * Wake up the dispatcher and wait until it processes all events and commands.
6705 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6706 * this method can be safely called from any thread, as long as you've ensured that
6707 * the work you are interested in completing has already been queued.
6708 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006709bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006710 /**
6711 * Timeout should represent the longest possible time that a device might spend processing
6712 * events and commands.
6713 */
6714 constexpr std::chrono::duration TIMEOUT = 100ms;
6715 std::unique_lock lock(mLock);
6716 mLooper->wake();
6717 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6718 return result == std::cv_status::no_timeout;
6719}
6720
Vishnu Naire798b472020-07-23 13:52:21 -07006721/**
6722 * Sets focus to the window identified by the token. This must be called
6723 * after updating any input window handles.
6724 *
6725 * Params:
6726 * request.token - input channel token used to identify the window that should gain focus.
6727 * request.focusedToken - the token that the caller expects currently to be focused. If the
6728 * specified token does not match the currently focused window, this request will be dropped.
6729 * If the specified focused token matches the currently focused window, the call will succeed.
6730 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6731 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6732 * when requesting the focus change. This determines which request gets
6733 * precedence if there is a focus change request from another source such as pointer down.
6734 */
Vishnu Nair958da932020-08-21 17:12:37 -07006735void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6736 { // acquire lock
6737 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006738 std::optional<FocusResolver::FocusChanges> changes =
6739 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6740 if (changes) {
6741 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006742 }
6743 } // release lock
6744 // Wake up poll loop since it may need to make new input dispatching choices.
6745 mLooper->wake();
6746}
6747
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006748void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6749 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006750 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006751 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6752 ? removedFocusedWindowHandle
6753 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6754 if (resolvedWindow == nullptr) {
6755 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006756 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006757 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6758 "focus left window");
6759 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6760 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006761 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006762 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006763 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006764 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006765 }
6766
Prabir Pradhan99987712020-11-10 18:43:05 -08006767 // If a window has pointer capture, then it must have focus. We need to ensure that this
6768 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6769 // If the window loses focus before it loses pointer capture, then the window can be in a state
6770 // where it has pointer capture but not focus, violating the contract. Therefore we must
6771 // dispatch the pointer capture event before the focus event. Since focus events are added to
6772 // the front of the queue (above), we add the pointer capture event to the front of the queue
6773 // after the focus events are added. This ensures the pointer capture event ends up at the
6774 // front.
6775 disablePointerCaptureForcedLocked();
6776
Vishnu Nairc519ff72021-01-21 08:23:08 -08006777 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006778 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006779 }
6780}
Vishnu Nair958da932020-08-21 17:12:37 -07006781
Prabir Pradhan99987712020-11-10 18:43:05 -08006782void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006783 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006784 return;
6785 }
6786
6787 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6788
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006789 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006790 setPointerCaptureLocked(false);
6791 }
6792
6793 if (!mWindowTokenWithPointerCapture) {
6794 // No need to send capture changes because no window has capture.
6795 return;
6796 }
6797
6798 if (mPendingEvent != nullptr) {
6799 // Move the pending event to the front of the queue. This will give the chance
6800 // for the pending event to be dropped if it is a captured event.
6801 mInboundQueue.push_front(mPendingEvent);
6802 mPendingEvent = nullptr;
6803 }
6804
6805 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006806 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006807 mInboundQueue.push_front(std::move(entry));
6808}
6809
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006810void InputDispatcher::setPointerCaptureLocked(bool enable) {
6811 mCurrentPointerCaptureRequest.enable = enable;
6812 mCurrentPointerCaptureRequest.seq++;
6813 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006814 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006815 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006816 };
6817 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006818}
6819
Vishnu Nair599f1412021-06-21 10:39:58 -07006820void InputDispatcher::displayRemoved(int32_t displayId) {
6821 { // acquire lock
6822 std::scoped_lock _l(mLock);
6823 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006824 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006825 setFocusedApplicationLocked(displayId, nullptr);
6826 // Call focus resolver to clean up stale requests. This must be called after input windows
6827 // have been removed for the removed display.
6828 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006829 // Reset pointer capture eligibility, regardless of previous state.
6830 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006831 // Remove the associated touch mode state.
6832 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006833 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006834 } // release lock
6835
6836 // Wake up poll loop since it may need to make new input dispatching choices.
6837 mLooper->wake();
6838}
6839
Patrick Williamsd828f302023-04-28 17:52:08 -05006840void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006841 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6842 {
6843 // acquire lock
6844 std::scoped_lock _l(mLock);
6845 logDispatchStateLocked();
6846 }
6847 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6848 result.error().message().c_str());
6849 };
chaviw15fab6f2021-06-07 14:15:52 -05006850 // The listener sends the windows as a flattened array. Separate the windows by display for
6851 // more convenient parsing.
6852 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006853 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006854 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006855 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006856 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006857
6858 { // acquire lock
6859 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006860
6861 // Ensure that we have an entry created for all existing displays so that if a displayId has
6862 // no windows, we can tell that the windows were removed from the display.
6863 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6864 handlesPerDisplay[displayId];
6865 }
6866
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006867 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006868 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006869 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6870 }
6871
6872 for (const auto& [displayId, handles] : handlesPerDisplay) {
6873 setInputWindowsLocked(handles, displayId);
6874 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006875
6876 if (update.vsyncId < mWindowInfosVsyncId) {
6877 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6878 ", current update vsync id: %" PRId64,
6879 mWindowInfosVsyncId, update.vsyncId);
6880 }
6881 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006882 }
6883 // Wake up poll loop since it may need to make new input dispatching choices.
6884 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006885}
6886
Vishnu Nair062a8672021-09-03 16:07:44 -07006887bool InputDispatcher::shouldDropInput(
6888 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006889 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6890 (windowHandle->getInfo()->inputConfig.test(
6891 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006892 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006893 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6894 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006895 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006896 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006897 windowHandle->getInfo()->displayId);
6898 return true;
6899 }
6900 return false;
6901}
6902
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006903void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006904 const gui::WindowInfosUpdate& update) {
6905 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006906}
6907
Arthur Hungdfd528e2021-12-08 13:23:04 +00006908void InputDispatcher::cancelCurrentTouch() {
6909 {
6910 std::scoped_lock _l(mLock);
6911 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006912 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006913 "cancel current touch");
6914 synthesizeCancelationEventsForAllConnectionsLocked(options);
6915
6916 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006917 }
6918 // Wake up poll loop since there might be work to do.
6919 mLooper->wake();
6920}
6921
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006922void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6923 std::scoped_lock _l(mLock);
6924 mMonitorDispatchingTimeout = timeout;
6925}
6926
Arthur Hungc539dbb2022-12-08 07:45:36 +00006927void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6928 const sp<WindowInfoHandle>& oldWindowHandle,
6929 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006930 TouchState& state, int32_t deviceId,
6931 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006932 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006933 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006934 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6935 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6936 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6937 newWindowHandle->getInfo()->inputConfig.test(
6938 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6939 const sp<WindowInfoHandle> oldWallpaper =
6940 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6941 const sp<WindowInfoHandle> newWallpaper =
6942 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6943 if (oldWallpaper == newWallpaper) {
6944 return;
6945 }
6946
6947 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006948 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006949 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006950 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006951 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006952 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006953 }
6954
6955 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006956 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6957 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006958 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006959 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006960 }
6961}
6962
6963void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6964 ftl::Flags<InputTarget::Flags> newTargetFlags,
6965 const sp<WindowInfoHandle> fromWindowHandle,
6966 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006967 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006968 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6970 fromWindowHandle->getInfo()->inputConfig.test(
6971 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6972 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6973 toWindowHandle->getInfo()->inputConfig.test(
6974 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6975
6976 const sp<WindowInfoHandle> oldWallpaper =
6977 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6978 const sp<WindowInfoHandle> newWallpaper =
6979 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6980 if (oldWallpaper == newWallpaper) {
6981 return;
6982 }
6983
6984 if (oldWallpaper != nullptr) {
6985 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6986 "transferring touch focus to another window");
6987 state.removeWindowByToken(oldWallpaper->getToken());
6988 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6989 }
6990
6991 if (newWallpaper != nullptr) {
6992 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006993 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006994 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6995 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006996 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006997 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006998 std::shared_ptr<Connection> wallpaperConnection =
6999 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007000 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007001 std::shared_ptr<Connection> toConnection =
7002 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007003 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7004 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7005 wallpaperFlags);
7006 }
7007 }
7008}
7009
7010sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7011 const sp<WindowInfoHandle>& windowHandle) const {
7012 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7013 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7014 bool foundWindow = false;
7015 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7016 if (!foundWindow && otherHandle != windowHandle) {
7017 continue;
7018 }
7019 if (windowHandle == otherHandle) {
7020 foundWindow = true;
7021 continue;
7022 }
7023
7024 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7025 return otherHandle;
7026 }
7027 }
7028 return nullptr;
7029}
7030
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007031void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7032 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007033 std::scoped_lock _l(mLock);
7034
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007035 mConfig.keyRepeatTimeout = timeout.count();
7036 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007037}
7038
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007039bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7040 DeviceId deviceId, int32_t pointerId) {
7041 std::scoped_lock _l(mLock);
7042 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7043 if (touchStateIt == mTouchStatesByDisplay.end()) {
7044 return false;
7045 }
7046 for (const TouchedWindow& window : touchStateIt->second.windows) {
7047 if (window.windowHandle->getToken() == token &&
7048 (window.hasTouchingPointer(deviceId, pointerId) ||
7049 window.hasHoveringPointer(deviceId, pointerId))) {
7050 return true;
7051 }
7052 }
7053 return false;
7054}
7055
Garfield Tane84e6f92019-08-29 17:28:41 -07007056} // namespace android::inputdispatcher