blob: ce9c6e027e405d10021c812513e8879f9286e566 [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 =
Prabir Pradhanc32a4112024-01-23 23:20:37 +0000396 inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
397 const 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.
Prabir Pradhanc32a4112024-01-23 23:20:37 +0000400 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
401 PointerCoords& newCoords = pointerCoords[i];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
Prabir Pradhanc32a4112024-01-23 23:20:37 +0000403 const auto pointerId = motionEntry.pointerProperties[i].id;
404 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
405
406 newCoords.copyFrom(motionEntry.pointerCoords[i]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700407 // First, apply the current pointer's transform to update the coordinates into
408 // window space.
Prabir Pradhanc32a4112024-01-23 23:20:37 +0000409 newCoords.transform(currTransform);
chaviw1ff3d1e2020-07-01 15:53:47 -0700410 // Next, apply the inverse transform of the normalized coordinates so the
411 // current coordinates are transformed into the normalized coordinate space.
Prabir Pradhanc32a4112024-01-23 23:20:37 +0000412 newCoords.transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 }
414
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700415 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000416 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
417 motionEntry.eventTime, motionEntry.deviceId,
418 motionEntry.source, motionEntry.displayId,
419 motionEntry.policyFlags, motionEntry.action,
420 motionEntry.actionButton, motionEntry.flags,
421 motionEntry.metaState, motionEntry.buttonState,
422 motionEntry.classification, motionEntry.edgeFlags,
423 motionEntry.xPrecision, motionEntry.yPrecision,
424 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
425 motionEntry.downTime, motionEntry.pointerProperties,
426 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000427
428 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700429 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700430 firstPointerTransform, inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000431 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000432 return dispatchEntry;
433}
434
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500435template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500437 if (lhs == nullptr && rhs == nullptr) {
438 return true;
439 }
440 if (lhs == nullptr || rhs == nullptr) {
441 return false;
442 }
443 return *lhs == *rhs;
444}
445
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000446KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000447 KeyEvent event;
448 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
449 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
450 entry.repeatCount, entry.downTime, entry.eventTime);
451 return event;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 // Do not keep track of gesture monitors. They receive every event and would disproportionately
456 // affect the statistics.
457 if (connection.monitor) {
458 return false;
459 }
460 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
461 if (!connection.responsive) {
462 return false;
463 }
464 return true;
465}
466
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000467bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
469 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000470 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
471 return false;
472 }
473 // Only track latency for events that originated from hardware
474 if (eventEntry.isSynthesized()) {
475 return false;
476 }
477 const EventEntry::Type& inputEventEntryType = eventEntry.type;
478 if (inputEventEntryType == EventEntry::Type::KEY) {
479 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
480 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
481 return false;
482 }
483 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
484 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
485 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
486 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
487 return false;
488 }
489 } else {
490 // Not a key or a motion
491 return false;
492 }
493 if (!shouldReportMetricsForConnection(connection)) {
494 return false;
495 }
496 return true;
497}
498
Prabir Pradhancef936d2021-07-21 16:17:52 +0000499/**
500 * Connection is responsive if it has no events in the waitQueue that are older than the
501 * current time.
502 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000503bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000504 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000505 for (const auto& dispatchEntry : connection.waitQueue) {
506 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000507 return false;
508 }
509 }
510 return true;
511}
512
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513// Returns true if the event type passed as argument represents a user activity.
514bool isUserActivityEvent(const EventEntry& eventEntry) {
515 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::CONFIGURATION_CHANGED:
517 case EventEntry::Type::DEVICE_RESET:
518 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000519 case EventEntry::Type::FOCUS:
520 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000521 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000522 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000523 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000524 case EventEntry::Type::KEY:
525 case EventEntry::Type::MOTION:
526 return true;
527 }
528}
529
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000531bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000532 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 const auto inputConfig = windowInfo.inputConfig;
534 if (windowInfo.displayId != displayId ||
535 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800536 return false;
537 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700538 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800539 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800540 return false;
541 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000542
543 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
544 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
545 // the window. Points on the right and bottom edges should not be inside the window, so we need
546 // to be careful about performing a hit test when the display is rotated, since the "right" and
547 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
548 // logical display in which WM determined the bounds. Perform the hit test in the logical
549 // display space to ensure these edges are considered correctly in all orientations.
550 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
551 const auto p = displayTransform.transform(x, y);
552 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800553 return false;
554 }
555 return true;
556}
557
Prabir Pradhand65552b2021-10-07 11:23:50 -0700558bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
559 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000560 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700561}
562
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800563// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000564// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
565// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
566// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800567// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000568bool canReceiveForegroundTouches(const WindowInfo& info) {
569 // A non-touchable window can still receive touch events (e.g. in the case of
570 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
571 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
572}
573
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000574bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700575 if (windowHandle == nullptr) {
576 return false;
577 }
578 const WindowInfo* windowInfo = windowHandle->getInfo();
579 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
580 return true;
581 }
582 return false;
583}
584
Prabir Pradhan5735a322022-04-11 17:23:34 +0000585// Checks targeted injection using the window's owner's uid.
586// Returns an empty string if an entry can be sent to the given window, or an error message if the
587// entry is a targeted injection whose uid target doesn't match the window owner.
588std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
589 const EventEntry& entry) {
590 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
591 // The event was not injected, or the injected event does not target a window.
592 return {};
593 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000595 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000596 return StringPrintf("No valid window target for injection into uid %s.",
597 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000600 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
601 "owned by uid %s.",
602 uid.toString().c_str(), window->getName().c_str(),
603 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000604 }
605 return {};
606}
607
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000608std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700609 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
610 // Always dispatch mouse events to cursor position.
611 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000612 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700613 }
614
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700615 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000616 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
617 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700618}
619
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700620std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
621 if (eventEntry.type == EventEntry::Type::KEY) {
622 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
623 return keyEntry.downTime;
624 } else if (eventEntry.type == EventEntry::Type::MOTION) {
625 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
626 return motionEntry.downTime;
627 }
628 return std::nullopt;
629}
630
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631/**
632 * Compare the old touch state to the new touch state, and generate the corresponding touched
633 * windows (== input targets).
634 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
635 * If the pointer just entered the new window, produce HOVER_ENTER.
636 * For pointers remaining in the window, produce HOVER_MOVE.
637 */
638std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
639 const TouchState& newTouchState,
640 const MotionEntry& entry) {
641 std::vector<TouchedWindow> out;
642 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700643
644 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
645 // ACTION_SCROLL events should not affect the hovering pointer dispatch
646 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000647 }
648
649 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800650 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000651
652 std::set<sp<WindowInfoHandle>> oldWindows;
653 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800654 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000655 }
656
657 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800658 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000659
660 // If the pointer is no longer in the new window set, send HOVER_EXIT.
661 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
662 if (newWindows.find(oldWindow) == newWindows.end()) {
663 TouchedWindow touchedWindow;
664 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000665 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000666 out.push_back(touchedWindow);
667 }
668 }
669
670 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
671 TouchedWindow touchedWindow;
672 touchedWindow.windowHandle = newWindow;
673 if (oldWindows.find(newWindow) == oldWindows.end()) {
674 // Any windows that have this pointer now, and didn't have it before, should get
675 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000676 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000677 } else {
678 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700679 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700680 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000681 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
682 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700683 // The Accessibility injected touch exploration event stream
684 // has known inconsistencies, so log ERROR instead of
685 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700686 severity = android::base::LogSeverity::ERROR;
687 }
688 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700689 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000690 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000691 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800692 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000693 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
694 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
695 }
696 out.push_back(touchedWindow);
697 }
698 return out;
699}
700
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800701template <typename T>
702std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
703 left.insert(left.end(), right.begin(), right.end());
704 return left;
705}
706
Harry Cuttsb166c002023-05-09 13:06:05 +0000707// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
708// both.
709void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
710 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
711 if (!window.windowHandle->getInfo()->inputConfig.test(
712 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
713 // In addition to TouchState, erase this window from the input targets! We don't have a
714 // good way to do this today except by adding a nested loop.
715 // TODO(b/282025641): simplify this code once InputTargets are being identified
716 // separately from TouchedWindows.
717 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800718 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000719 });
720 return true;
721 }
722 return false;
723 });
724}
725
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700726/**
727 * In general, touch should be always split between windows. Some exceptions:
728 * 1. Don't split touch if all of the below is true:
729 * (a) we have an active pointer down *and*
730 * (b) a new pointer is going down that's from the same device *and*
731 * (c) the window that's receiving the current pointer does not support split touch.
732 * 2. Don't split mouse events
733 */
734bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
735 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
736 // We should never split mouse events
737 return false;
738 }
739 for (const TouchedWindow& touchedWindow : touchState.windows) {
740 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
741 // Spy windows should not affect whether or not touch is split.
742 continue;
743 }
744 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
745 continue;
746 }
747 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
748 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
749 // Wallpaper window should not affect whether or not touch is split
750 continue;
751 }
752
753 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
754 return false;
755 }
756 }
757 return true;
758}
759
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700760/**
761 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
762 */
763bool isStylusActiveInDisplay(
764 int32_t displayId,
765 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
766 const auto it = touchStatesByDisplay.find(displayId);
767 if (it == touchStatesByDisplay.end()) {
768 return false;
769 }
770 const TouchState& state = it->second;
771 return state.hasActiveStylus();
772}
773
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800774Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
775 struct HashFunction {
776 size_t operator()(const WindowInfo& info) const { return info.id; }
777 };
778
779 std::unordered_set<WindowInfo, HashFunction> windowSet;
780 for (const WindowInfo& info : update.windowInfos) {
781 const auto [_, inserted] = windowSet.insert(info);
782 if (!inserted) {
783 return Error() << "Duplicate entry for " << info;
784 }
785 }
786 return {};
787}
788
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800789int32_t getUserActivityEventType(const EventEntry& eventEntry) {
790 switch (eventEntry.type) {
791 case EventEntry::Type::KEY: {
792 return USER_ACTIVITY_EVENT_BUTTON;
793 }
794 case EventEntry::Type::MOTION: {
795 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
796 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
797 return USER_ACTIVITY_EVENT_TOUCH;
798 }
799 return USER_ACTIVITY_EVENT_OTHER;
800 }
801 default: {
802 LOG_ALWAYS_FATAL("%s events are not user activity",
803 ftl::enum_string(eventEntry.type).c_str());
804 }
805 }
806}
807
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000808std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
809 CancelationOptions::Mode mode) {
810 switch (mode) {
811 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
812 return {true, true};
813 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
814 return {true, false};
815 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
816 return {false, true};
817 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
818 return {false, true};
819 }
820}
821
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000822} // namespace
823
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824// --- InputDispatcher ---
825
Prabir Pradhana41d2442023-04-20 21:30:40 +0000826InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000827 : InputDispatcher(policy,
828 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
829 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000830
831InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
832 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700833 : mPolicy(policy),
834 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700835 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800836 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800837 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700838 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800839 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700840 mDispatchEnabled(false),
841 mDispatchFrozen(false),
842 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100843 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000844 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800845 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000846 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000847 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700848 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800849 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700851 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700852#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700853 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700854#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700855 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000856
857 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000858 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000859 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800860
861 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862}
863
864InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
Prabir Pradhancef936d2021-07-21 16:17:52 +0000867 resetKeyRepeatLocked();
868 releasePendingEventLocked();
869 drainInboundQueueLocked();
870 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000872 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700873 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800874 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876}
877
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700878status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700879 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700880 return ALREADY_EXISTS;
881 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700882 mThread = std::make_unique<InputThread>(
883 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
884 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700885}
886
887status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700888 if (mThread && mThread->isCallingThread()) {
889 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700890 return INVALID_OPERATION;
891 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700892 mThread.reset();
893 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700894}
895
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700897 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800899 std::scoped_lock _l(mLock);
900 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 // Run a dispatch loop if there are no pending commands.
903 // The dispatch loop might enqueue commands to run afterwards.
904 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800905 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907
908 // Run all pending commands if there are any.
909 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000910 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700911 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 // If we are still waiting for ack on some events,
915 // we might have to wake up earlier to check if an app is anr'ing.
916 const nsecs_t nextAnrCheck = processAnrsLocked();
917 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
918
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800919 // We are about to enter an infinitely long sleep, because we have no commands or
920 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700921 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800922 mDispatcherEnteredIdle.notify_all();
923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 } // release lock
925
926 // Wait for callback or timeout or wake. (make sure we round up, not down)
927 nsecs_t currentTime = now();
928 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
929 mLooper->pollOnce(timeoutMillis);
930}
931
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500933 * Raise ANR if there is no focused window.
934 * Before the ANR is raised, do a final state check:
935 * 1. The currently focused application must be the same one we are waiting for.
936 * 2. Ensure we still don't have a focused window.
937 */
938void InputDispatcher::processNoFocusedWindowAnrLocked() {
939 // Check if the application that we are waiting for is still focused.
940 std::shared_ptr<InputApplicationHandle> focusedApplication =
941 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
942 if (focusedApplication == nullptr ||
943 focusedApplication->getApplicationToken() !=
944 mAwaitedFocusedApplication->getApplicationToken()) {
945 // Unexpected because we should have reset the ANR timer when focused application changed
946 ALOGE("Waited for a focused window, but focused application has already changed to %s",
947 focusedApplication->getName().c_str());
948 return; // The focused application has changed.
949 }
950
chaviw98318de2021-05-19 16:45:23 -0500951 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500952 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
953 if (focusedWindowHandle != nullptr) {
954 return; // We now have a focused window. No need for ANR.
955 }
956 onAnrLocked(mAwaitedFocusedApplication);
957}
958
959/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700960 * Check if any of the connections' wait queues have events that are too old.
961 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
962 * Return the time at which we should wake up next.
963 */
964nsecs_t InputDispatcher::processAnrsLocked() {
965 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700966 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
968 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
969 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500970 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700971 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500972 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700973 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700974 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500975 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700976 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
977 }
978 }
979
980 // Check if any connection ANRs are due
981 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
982 if (currentTime < nextAnrCheck) { // most likely scenario
983 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
984 }
985
986 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700987 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700988 if (connection == nullptr) {
989 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
990 return nextAnrCheck;
991 }
992 connection->responsive = false;
993 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800994 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000995 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700996 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700997}
998
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800999std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001000 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001001 if (connection->monitor) {
1002 return mMonitorDispatchingTimeout;
1003 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001004 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001005 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001006 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001007 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001008 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001009}
1010
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001011void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 nsecs_t currentTime = now();
1013
Jeff Browndc5992e2014-04-11 01:27:26 -07001014 // Reset the key repeat timer whenever normal dispatch is suspended while the
1015 // device is in a non-interactive state. This is to ensure that we abort a key
1016 // repeat if the device is just coming out of sleep.
1017 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 resetKeyRepeatLocked();
1019 }
1020
1021 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1022 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001023 if (DEBUG_FOCUS) {
1024 ALOGD("Dispatch frozen. Waiting some more.");
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 return;
1027 }
1028
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 // Ready to start a new event.
1030 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 // Synthesize a key repeat if appropriate.
1034 if (mKeyRepeatState.lastKeyEntry) {
1035 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1036 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1037 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001038 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040 }
1041
1042 // Nothing to do if there is no pending event.
1043 if (!mPendingEvent) {
1044 return;
1045 }
1046 } else {
1047 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 mPendingEvent = mInboundQueue.front();
1049 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 traceInboundQueueLengthLocked();
1051 }
1052
1053 // Poke user activity for this event.
1054 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001055 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058
1059 // Now we have an event to dispatch.
1060 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001065 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069
1070 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001071 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
1073
1074 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 const ConfigurationChangedEntry& typedEntry =
1077 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 break;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001083 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 const DeviceResetEntry& typedEntry =
1085 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 break;
1089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001091 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001092 std::shared_ptr<const FocusEntry> typedEntry =
1093 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001094 dispatchFocusLocked(currentTime, typedEntry);
1095 done = true;
1096 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1097 break;
1098 }
1099
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001100 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001101 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001102 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1103 done = true;
1104 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1105 break;
1106 }
1107
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1109 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001110 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001111 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1112 done = true;
1113 break;
1114 }
1115
arthurhungb89ccb02020-12-30 16:19:01 +08001116 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 std::shared_ptr<const DragEntry> typedEntry =
1118 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001119 dispatchDragLocked(currentTime, typedEntry);
1120 done = true;
1121 break;
1122 }
1123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001125 std::shared_ptr<const KeyEntry> keyEntry =
1126 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1131 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001133 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001134 if (done && mTracer) {
1135 ensureEventTraced(*keyEntry);
1136 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 break;
1139 }
1140
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001141 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001142 std::shared_ptr<const MotionEntry> motionEntry =
1143 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001144 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001145 // The event is stale. However, only drop stale events if there isn't an ongoing
1146 // gesture. That would allow us to complete the processing of the current stroke.
1147 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1148 if (touchStateIt != mTouchStatesByDisplay.end()) {
1149 const TouchState& touchState = touchStateIt->second;
1150 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1151 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1152 dropReason = DropReason::STALE;
1153 }
1154 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001157 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1158 // Only drop events that are focus-dispatched.
1159 dropReason = DropReason::BLOCKED;
1160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001163 if (done && mTracer) {
1164 ensureEventTraced(*motionEntry);
1165 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
Chris Yef59a2f42020-10-16 12:55:26 -07001169
1170 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001171 std::shared_ptr<const SensorEntry> sensorEntry =
1172 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001173
Chris Yef59a2f42020-10-16 12:55:26 -07001174 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1175 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1176 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1177 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1178 dropReason = DropReason::STALE;
1179 }
1180 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1181 done = true;
1182 break;
1183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
1185
1186 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
Michael Wright3a981722015-06-10 15:26:13 +01001190 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191
1192 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001193 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195}
1196
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001197bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001198 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001199}
1200
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201/**
1202 * Return true if the events preceding this incoming motion event should be dropped
1203 * Return false otherwise (the default behaviour)
1204 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001205bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001207 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001208
1209 // Optimize case where the current application is unresponsive and the user
1210 // decides to touch a window in a different application.
1211 // If the application takes too long to catch up then we drop all events preceding
1212 // the touch into the other window.
1213 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001214 const int32_t displayId = motionEntry.displayId;
1215 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001216 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001217
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001218 sp<WindowInfoHandle> touchedWindowHandle =
1219 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001220 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001221 touchedWindowHandle->getApplicationToken() !=
1222 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001223 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 ALOGI("Pruning input queue because user touched a different application while waiting "
1225 "for %s",
1226 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001227 return true;
1228 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001229
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001230 // Alternatively, maybe there's a spy window that could handle this event.
1231 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1232 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1233 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001234 const std::shared_ptr<Connection> connection =
1235 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001236 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001237 // This spy window could take more input. Drop all events preceding this
1238 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001239 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001240 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001241 mAwaitedFocusedApplication->getName().c_str());
1242 return true;
1243 }
1244 }
1245 }
1246
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 return false;
1248}
1249
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001251 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001253 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 traceInboundQueueLengthLocked();
1255
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001256 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001257 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001258 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1259 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001260
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001262 if (mTracer) {
1263 ensureEventTraced(keyEntry);
1264 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001265
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001266 // If a new up event comes in, and the pending event with same key code has been asked
1267 // to try again later because of the policy. We have to reset the intercept key wake up
1268 // time for it may have been handled in the policy and could be dropped.
1269 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1270 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001271 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001272 if (pendingKey.keyCode == keyEntry.keyCode &&
1273 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001274 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1275 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001276 pendingKey.interceptKeyWakeupTime = 0;
1277 needWake = true;
1278 }
1279 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 break;
1281 }
1282
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001283 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001284 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1285 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001286 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1287 if (mTracer) {
1288 ensureEventTraced(motionEntry);
1289 }
1290 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001292 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001294
1295 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1296 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1297 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1298 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1299 // and some other events have not yet been processed, the dispatcher will wait for
1300 // these events to be processed before dispatching the key event. This is because
1301 // the unprocessed events may cause the focus to change (for example, by launching a
1302 // new window or tapping a different window). To prevent waiting too long, we force
1303 // the key to be sent to the currently focused window when a new tap comes in.
1304 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1305 "just send the pending key event to the currently focused window.");
1306 mKeyIsWaitingForEventsTimeout = now();
1307 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001310 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001311 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1312 break;
1313 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001314 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001315 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001316 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001317 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001318 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1319 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001320 // nothing to do
1321 break;
1322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
1324
1325 return needWake;
1326}
1327
Prabir Pradhan24047542023-11-02 17:14:59 +00001328void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001329 // Do not store sensor event in recent queue to avoid flooding the queue.
1330 if (entry->type != EventEntry::Type::SENSOR) {
1331 mRecentQueue.push_back(entry);
1332 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001333 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001334 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336}
1337
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001338sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1339 bool isStylus,
1340 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001342 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001343 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001344 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001345 continue;
1346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001348 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001349 if (!info.isSpy() &&
1350 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001351 return windowHandle;
1352 }
1353 }
1354 return nullptr;
1355}
1356
1357std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001358 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001359 if (touchedWindow == nullptr) {
1360 return {};
1361 }
1362 // Traverse windows from front to back until we encounter the touched window.
1363 std::vector<InputTarget> outsideTargets;
1364 const auto& windowHandles = getWindowHandlesLocked(displayId);
1365 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1366 if (windowHandle == touchedWindow) {
1367 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1368 // below the touched window will not get ACTION_OUTSIDE event.
1369 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001370 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001371
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001372 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001373 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001374 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1375 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001376 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1377 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001378 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001381 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382}
1383
Prabir Pradhand65552b2021-10-07 11:23:50 -07001384std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001385 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001386 // Traverse windows from front to back and gather the touched spy windows.
1387 std::vector<sp<WindowInfoHandle>> spyWindows;
1388 const auto& windowHandles = getWindowHandlesLocked(displayId);
1389 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1390 const WindowInfo& info = *windowHandle->getInfo();
1391
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001392 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001393 continue;
1394 }
1395 if (!info.isSpy()) {
1396 // The first touched non-spy window was found, so return the spy windows touched so far.
1397 return spyWindows;
1398 }
1399 spyWindows.push_back(windowHandle);
1400 }
1401 return spyWindows;
1402}
1403
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 const char* reason;
1406 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001407 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001408 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001409 ALOGD("Dropped event because policy consumed it.");
1410 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 reason = "inbound event was dropped because the policy consumed it";
1412 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001413 case DropReason::DISABLED:
1414 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 ALOGI("Dropped event because input dispatch is disabled.");
1416 }
1417 reason = "inbound event was dropped because input dispatch is disabled";
1418 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001419 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001420 LOG(INFO) << "Dropping because the current application is not responding and the user "
1421 "has started interacting with a different application: "
1422 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 reason = "inbound event was dropped because the current application is not responding "
1424 "and the user has started interacting with a different application";
1425 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001426 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 ALOGI("Dropped event because it is stale.");
1428 reason = "inbound event was dropped because it is stale";
1429 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001430 case DropReason::NO_POINTER_CAPTURE:
1431 ALOGI("Dropped event because there is no window with Pointer Capture.");
1432 reason = "inbound event was dropped because there is no window with Pointer Capture";
1433 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001434 case DropReason::NOT_DROPPED: {
1435 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
1439
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001440 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001441 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001442 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001443 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1444 options.displayId = keyEntry.displayId;
1445 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001447 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001449 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001450 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1451 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001452 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001453 options.displayId = motionEntry.displayId;
1454 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 synthesizeCancelationEventsForAllConnectionsLocked(options);
1456 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001457 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1458 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001459 options.displayId = motionEntry.displayId;
1460 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001461 synthesizeCancelationEventsForAllConnectionsLocked(options);
1462 }
1463 break;
1464 }
Chris Yef59a2f42020-10-16 12:55:26 -07001465 case EventEntry::Type::SENSOR: {
1466 break;
1467 }
arthurhungb89ccb02020-12-30 16:19:01 +08001468 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1469 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001470 break;
1471 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001472 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001473 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001474 case EventEntry::Type::CONFIGURATION_CHANGED:
1475 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001476 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001477 break;
1478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 }
1480}
1481
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001483 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484}
1485
Prabir Pradhancef936d2021-07-21 16:17:52 +00001486bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001487 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return false;
1489 }
1490
1491 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001492 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001493 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001494 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1495 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001496 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 return true;
1498}
1499
Prabir Pradhancef936d2021-07-21 16:17:52 +00001500void InputDispatcher::postCommandLocked(Command&& command) {
1501 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502}
1503
1504void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001505 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001506 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001507 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 releaseInboundEventLocked(entry);
1509 }
1510 traceInboundQueueLengthLocked();
1511}
1512
1513void InputDispatcher::releasePendingEventLocked() {
1514 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001516 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518}
1519
Prabir Pradhan24047542023-11-02 17:14:59 +00001520void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001521 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001522 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_DISPATCH_CYCLE) {
1524 ALOGD("Injected inbound event was dropped.");
1525 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001526 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 }
1528 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001529 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
1531 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532}
1533
1534void InputDispatcher::resetKeyRepeatLocked() {
1535 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001536 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538}
1539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001540std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001541 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542
Michael Wright2e732952014-09-24 13:26:59 -07001543 uint32_t policyFlags = entry->policyFlags &
1544 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001546 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001547 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1548 currentTime, entry->deviceId, entry->source,
1549 entry->displayId, policyFlags, entry->action, entry->flags,
1550 entry->keyCode, entry->scanCode, entry->metaState,
1551 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001554 if (mTracer) {
1555 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1556 }
1557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001558 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561}
1562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001564 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1566 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568
1569 // Reset key repeating in case a keyboard device was added or removed or something.
1570 resetKeyRepeatLocked();
1571
1572 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001573 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1574 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001575 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001576 };
1577 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return true;
1579}
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1582 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1584 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1585 entry.deviceId);
1586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
liushenxiang42232912021-05-21 20:24:09 +08001588 // Reset key repeating in case a keyboard device was disabled or enabled.
1589 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1590 resetKeyRepeatLocked();
1591 }
1592
Michael Wrightfb04fd52022-11-24 22:31:11 +00001593 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001594 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001596
1597 // Remove all active pointers from this device
1598 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1599 touchState.removeAllPointersForDevice(entry.deviceId);
1600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 return true;
1602}
1603
Vishnu Nairad321cd2020-08-20 16:40:21 -07001604void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001605 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001606 if (mPendingEvent != nullptr) {
1607 // Move the pending event to the front of the queue. This will give the chance
1608 // for the pending event to get dispatched to the newly focused window
1609 mInboundQueue.push_front(mPendingEvent);
1610 mPendingEvent = nullptr;
1611 }
1612
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001613 std::unique_ptr<FocusEntry> focusEntry =
1614 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1615 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001616
1617 // This event should go to the front of the queue, but behind all other focus events
1618 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001619 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1620 [](const std::shared_ptr<const EventEntry>& event) {
1621 return event->type == EventEntry::Type::FOCUS;
1622 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001623
1624 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001625 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001626}
1627
Prabir Pradhan24047542023-11-02 17:14:59 +00001628void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1629 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001630 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1631 if (connection == nullptr) {
1632 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001633 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001634 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001635 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001636 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001637 std::string reason = std::string("reason=").append(entry->reason);
1638 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001639 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001640}
1641
Prabir Pradhan99987712020-11-10 18:43:05 -08001642void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001643 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001644 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001645 dropReason = DropReason::NOT_DROPPED;
1646
Prabir Pradhan99987712020-11-10 18:43:05 -08001647 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001648 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001649
1650 if (entry->pointerCaptureRequest.enable) {
1651 // Enable Pointer Capture.
1652 if (haveWindowWithPointerCapture &&
1653 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001654 // This can happen if pointer capture is disabled and re-enabled before we notify the
1655 // app of the state change, so there is no need to notify the app.
1656 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1657 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001658 }
1659 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 // This can happen if a window requests capture and immediately releases capture.
1661 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001663 return;
1664 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001665 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1666 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1667 return;
1668 }
1669
Vishnu Nairc519ff72021-01-21 08:23:08 -08001670 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001671 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1672 mWindowTokenWithPointerCapture = token;
1673 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001674 // Disable Pointer Capture.
1675 // We do not check if the sequence number matches for requests to disable Pointer Capture
1676 // for two reasons:
1677 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1678 // to disable capture with the same sequence number: one generated by
1679 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1680 // Capture being disabled in InputReader.
1681 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1682 // actual Pointer Capture state that affects events being generated by input devices is
1683 // in InputReader.
1684 if (!haveWindowWithPointerCapture) {
1685 // Pointer capture was already forcefully disabled because of focus change.
1686 dropReason = DropReason::NOT_DROPPED;
1687 return;
1688 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001689 token = mWindowTokenWithPointerCapture;
1690 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001691 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001692 setPointerCaptureLocked(false);
1693 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001694 }
1695
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001696 auto connection = getConnectionLocked(token);
1697 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001698 // Window has gone away, clean up Pointer Capture state.
1699 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001700 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001701 setPointerCaptureLocked(false);
1702 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001703 return;
1704 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001705 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001706 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001707
1708 dropReason = DropReason::NOT_DROPPED;
1709}
1710
Prabir Pradhan24047542023-11-02 17:14:59 +00001711void InputDispatcher::dispatchTouchModeChangeLocked(
1712 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001713 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001714 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001715 if (windowHandles.empty()) {
1716 return;
1717 }
1718 const std::vector<InputTarget> inputTargets =
1719 getInputTargetsFromWindowHandlesLocked(windowHandles);
1720 if (inputTargets.empty()) {
1721 return;
1722 }
1723 entry->dispatchInProgress = true;
1724 dispatchEventLocked(currentTime, entry, inputTargets);
1725}
1726
1727std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1728 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1729 std::vector<InputTarget> inputTargets;
1730 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001731 const sp<IBinder>& token = handle->getToken();
1732 if (token == nullptr) {
1733 continue;
1734 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001735 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1736 if (connection == nullptr) {
1737 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001738 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001739 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001740 }
1741 return inputTargets;
1742}
1743
Prabir Pradhan24047542023-11-02 17:14:59 +00001744bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001745 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001747 if (!entry->dispatchInProgress) {
1748 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1749 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1750 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1751 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001752 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 // We have seen two identical key downs in a row which indicates that the device
1754 // driver is automatically generating key repeats itself. We take note of the
1755 // repeat here, but we disable our own next key repeat timer since it is clear that
1756 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001757 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1758 // Make sure we don't get key down from a different device. If a different
1759 // device Id has same key pressed down, the new device Id will replace the
1760 // current one to hold the key repeat with repeat count reset.
1761 // In the future when got a KEY_UP on the device id, drop it and do not
1762 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1764 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001765 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 } else {
1767 // Not a repeat. Save key down state in case we do see a repeat later.
1768 resetKeyRepeatLocked();
1769 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1770 }
1771 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001772 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1773 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001774 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001775 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001776 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1777 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 resetKeyRepeatLocked();
1780 }
1781
1782 if (entry->repeatCount == 1) {
1783 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1784 } else {
1785 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1786 }
1787
1788 entry->dispatchInProgress = true;
1789
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792
1793 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001794 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001796 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 return false; // wait until next wakeup
1798 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001799 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 entry->interceptKeyWakeupTime = 0;
1801 }
1802
1803 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001804 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001806 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001807 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001808
1809 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1810 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1811 };
1812 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001813 // Poke user activity for keys not passed to user
1814 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 return false; // wait for the command to run
1816 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001817 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001819 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001820 if (*dropReason == DropReason::NOT_DROPPED) {
1821 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823 }
1824
1825 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001826 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001827 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001828 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1829 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001830 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001831 // Poke user activity for undispatched keys
1832 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 return true;
1834 }
1835
1836 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001837 InputEventInjectionResult injectionResult;
1838 sp<WindowInfoHandle> focusedWindow =
1839 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1840 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001841 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 return false;
1843 }
1844
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001845 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 return true;
1848 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001849 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1850
1851 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001852 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1853 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001855 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001856 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001858 if (mTracer) {
1859 ensureEventTraced(*entry);
1860 for (const auto& target : inputTargets) {
1861 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1862 }
1863 }
1864
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 // Dispatch the key.
1866 dispatchEventLocked(currentTime, entry, inputTargets);
1867 return true;
1868}
1869
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1872 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1873 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1874 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1875 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1876 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1877 entry.metaState, entry.repeatCount, entry.downTime);
1878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879}
1880
Prabir Pradhancef936d2021-07-21 16:17:52 +00001881void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001882 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001883 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001884 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1885 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1886 "source=0x%x, sensorType=%s",
1887 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001888 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001889 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001890 auto command = [this, entry]() REQUIRES(mLock) {
1891 scoped_unlock unlock(mLock);
1892
1893 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001894 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001895 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001896 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1897 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001898 };
1899 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001900}
1901
1902bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001903 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1904 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001905 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001906 }
Chris Yef59a2f42020-10-16 12:55:26 -07001907 { // acquire lock
1908 std::scoped_lock _l(mLock);
1909
1910 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001911 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001912 if (entry->type == EventEntry::Type::SENSOR) {
1913 it = mInboundQueue.erase(it);
1914 releaseInboundEventLocked(entry);
1915 }
1916 }
1917 }
1918 return true;
1919}
1920
Prabir Pradhan24047542023-11-02 17:14:59 +00001921bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1922 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001923 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001924 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001926 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 entry->dispatchInProgress = true;
1928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001929 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 }
1931
1932 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001933 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001934 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1936 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 return true;
1938 }
1939
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001940 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941
1942 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001943 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 if (isPointerEvent) {
1947 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001948
1949 if (mDragState &&
1950 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1951 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1952 pilferPointersLocked(mDragState->dragWindow->getToken());
1953 }
1954
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001955 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001956 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001957 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1958 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 } else {
1960 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001961 sp<WindowInfoHandle> focusedWindow =
1962 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1963 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1964 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001965 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1966 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1967 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 return false;
1972 }
1973
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001974 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001975 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001976 return true;
1977 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001978 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001979 CancelationOptions::Mode mode(
1980 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1981 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001982 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001983 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 return true;
1986 }
1987
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001988 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001991 if (mTracer) {
1992 ensureEventTraced(*entry);
1993 for (const auto& target : inputTargets) {
1994 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1995 }
1996 }
1997
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 dispatchEventLocked(currentTime, entry, inputTargets);
2000 return true;
2001}
2002
chaviw98318de2021-05-19 16:45:23 -05002003void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002004 bool isExiting, const int32_t rawX,
2005 const int32_t rawY) {
2006 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002007 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002008 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2009 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002010
2011 enqueueInboundEventLocked(std::move(dragEntry));
2012}
2013
Prabir Pradhan24047542023-11-02 17:14:59 +00002014void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2015 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002016 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2017 if (connection == nullptr) {
2018 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002019 }
arthurhungb89ccb02020-12-30 16:19:01 +08002020 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002021 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002022}
2023
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002025 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002026 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002027 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002028 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002029 "metaState=0x%x, buttonState=0x%x,"
2030 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002031 prefix, entry.eventTime, entry.deviceId,
2032 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2033 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2034 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2035 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002037 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002038 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002039 "x=%f, y=%f, pressure=%f, size=%f, "
2040 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2041 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002042 i, entry.pointerProperties[i].id,
2043 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002044 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2045 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2046 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2047 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2048 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2049 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2050 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2051 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2052 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055}
2056
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002057void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002058 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002059 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002061 if (DEBUG_DISPATCH_CYCLE) {
2062 ALOGD("dispatchEventToCurrentInputTargets");
2063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002065 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002066
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2068
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002069 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002071 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002072 std::shared_ptr<Connection> connection = inputTarget.connection;
2073 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 }
2075}
2076
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002077void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2079 // If the policy decides to close the app, we will get a channel removal event via
2080 // unregisterInputChannel, and will clean up the connection that way. We are already not
2081 // sending new pointers to the connection when it blocked, but focused events will continue to
2082 // pile up.
2083 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002084 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002085 if (connection->status != Connection::Status::NORMAL) {
2086 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002088 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2089 "application not responding");
2090
2091 sp<WindowInfoHandle> windowHandle;
2092 if (!connection->monitor) {
2093 windowHandle = getWindowHandleLocked(connection->getToken());
2094 if (windowHandle == nullptr) {
2095 // The window that is receiving this ANR was removed, so there is no need to generate
2096 // cancellations, because the cancellations would have already been generated when
2097 // the window was removed.
2098 return;
2099 }
2100 }
2101 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102}
2103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002105 if (DEBUG_FOCUS) {
2106 ALOGD("Resetting ANR timeouts.");
2107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108
2109 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002111 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112}
2113
Tiger Huang721e26f2018-07-24 22:26:19 +08002114/**
2115 * Get the display id that the given event should go to. If this event specifies a valid display id,
2116 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2117 * Focused display is the display that the user most recently interacted with.
2118 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002120 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002121 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002122 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2124 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002125 break;
2126 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002127 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002128 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2129 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002130 break;
2131 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002132 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002133 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002134 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002135 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002136 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002137 case EventEntry::Type::SENSOR:
2138 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002139 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 return ADISPLAY_ID_NONE;
2141 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002142 }
2143 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2144}
2145
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2147 const char* focusedWindowName) {
2148 if (mAnrTracker.empty()) {
2149 // already processed all events that we waited for
2150 mKeyIsWaitingForEventsTimeout = std::nullopt;
2151 return false;
2152 }
2153
2154 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2155 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002156 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002157 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002158 std::chrono::duration_cast<std::chrono::nanoseconds>(
2159 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002160 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 return true;
2162 }
2163
2164 // We still have pending events, and already started the timer
2165 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2166 return true; // Still waiting
2167 }
2168
2169 // Waited too long, and some connection still hasn't processed all motions
2170 // Just send the key to the focused window
2171 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2172 focusedWindowName);
2173 mKeyIsWaitingForEventsTimeout = std::nullopt;
2174 return false;
2175}
2176
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002178 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002180 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181
Tiger Huang721e26f2018-07-24 22:26:19 +08002182 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002183 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002184 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002185 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2186
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 // If there is no currently focused window and no focused application
2188 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002189 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2190 ALOGI("Dropping %s event because there is no focused window or focused application in "
2191 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002192 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002193 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 }
2195
Vishnu Nair062a8672021-09-03 16:07:44 -07002196 // Drop key events if requested by input feature
2197 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002198 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002199 }
2200
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2202 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2203 // start interacting with another application via touch (app switch). This code can be removed
2204 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2205 // an app is expected to have a focused window.
2206 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2207 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2208 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002209 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2210 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2211 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002212 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002213 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002214 ALOGW("Waiting because no window has focus but %s may eventually add a "
2215 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002216 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002217 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002218 outInjectionResult = InputEventInjectionResult::PENDING;
2219 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002220 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2221 // Already raised ANR. Drop the event
2222 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002223 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002225 } else {
2226 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::PENDING;
2228 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 }
2230 }
2231
2232 // we have a valid, non-null focused window
2233 resetNoFocusedWindowTimeoutLocked();
2234
Prabir Pradhan5735a322022-04-11 17:23:34 +00002235 // Verify targeted injection.
2236 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2237 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002238 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2239 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
2241
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002242 if (focusedWindowHandle->getInfo()->inputConfig.test(
2243 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002245 outInjectionResult = InputEventInjectionResult::PENDING;
2246 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 }
2248
2249 // If the event is a key event, then we must wait for all previous events to
2250 // complete before delivering it because previous events may have the
2251 // side-effect of transferring focus to a different window and we want to
2252 // ensure that the following keys are sent to the new window.
2253 //
2254 // Suppose the user touches a button in a window then immediately presses "A".
2255 // If the button causes a pop-up window to appear then we want to ensure that
2256 // the "A" key is delivered to the new pop-up window. This is because users
2257 // often anticipate pending UI changes when typing on a keyboard.
2258 // To obtain this behavior, we must serialize key events with respect to all
2259 // prior input events.
2260 if (entry.type == EventEntry::Type::KEY) {
2261 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002262 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002263 outInjectionResult = InputEventInjectionResult::PENDING;
2264 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002268 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2269 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270}
2271
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002272/**
2273 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2274 * that are currently unresponsive.
2275 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002276std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2277 const std::vector<Monitor>& monitors) const {
2278 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002280 [](const Monitor& monitor) REQUIRES(mLock) {
2281 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 if (!connection->responsive) {
2283 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002284 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002285 return false;
2286 }
2287 return true;
2288 });
2289 return responsiveMonitors;
2290}
2291
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002292std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002293 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002294 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002295 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002297 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 // For security reasons, we defer updating the touch state until we are sure that
2299 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002300 const int32_t displayId = entry.displayId;
2301 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002302 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303
2304 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002305 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 // Copy current touch state into tempTouchState.
2308 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2309 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002310 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002312 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2313 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002314 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002315 }
2316
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002317 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318
2319 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2320 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2321 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002322 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2323 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002324 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002325 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2326 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002327 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2328 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2329 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002330 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002331
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002332 if (newGesture) {
2333 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002334 }
2335
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002336 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2337 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2338 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002341 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002342 if (wasDown) {
2343 // Started hovering, but the device is already down: reject the hover event
2344 LOG(ERROR) << "Got hover event " << entry.getDescription()
2345 << " but the device is already down " << oldState->dump();
2346 outInjectionResult = InputEventInjectionResult::FAILED;
2347 return {};
2348 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002349 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2350 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002351 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002352 }
2353
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2355 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002356 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002357 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002358 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002359 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2360 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002361 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002362 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002363 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002364
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002365 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002366 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002369 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002370 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002372 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002373 }
2374
Prabir Pradhan5735a322022-04-11 17:23:34 +00002375 // Verify targeted injection.
2376 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2377 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002378 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002379 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002380 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002381 }
2382
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002383 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002384 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2386 // New window supports splitting, but we should never split mouse events.
2387 isSplit = !isFromMouse;
2388 } else if (isSplit) {
2389 // New window does not support splitting but we have already split events.
2390 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002391 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2392 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002393 newTouchedWindowHandle = nullptr;
2394 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002395 } else {
2396 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002397 // be delivered to a new window which supports split touch. Pointers from a mouse device
2398 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002399 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002400 }
2401
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002402 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002403 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002405 // Process the foreground window first so that it is the first to receive the event.
2406 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002407 }
2408
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002409 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002410 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2411 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002412 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002413 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002414 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002415 }
2416
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002417 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002418 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002419 continue;
2420 }
2421
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002422 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002423 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002424 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002425 }
2426
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002427 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002428 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002429
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002430 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2431 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002432 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002433 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434
2435 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002436 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002437 }
2438 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002439 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002440 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002441 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002442 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002443
2444 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002445
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002446 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002447 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2448 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002449 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002450 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002451 isDownOrPointerDown
2452 ? std::make_optional(entry.eventTime)
2453 : std::nullopt);
2454 // If this is the pointer going down and the touched window has a wallpaper
2455 // then also add the touched wallpaper windows so they are locked in for the
2456 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2457 // SCROLL because the wallpaper engine only supports touch events. We would need to
2458 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2459 // handle these events.
2460 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002461 windowHandle->getInfo()->inputConfig.test(
2462 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2463 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2464 if (wallpaper != nullptr) {
2465 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2466 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002467 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002468 if (isSplit) {
2469 wallpaperFlags |= InputTarget::Flags::SPLIT;
2470 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002471 tempTouchState.addOrUpdateWindow(wallpaper,
2472 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002473 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002474 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002475 }
2476 }
2477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002479
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002480 // If a window is already pilfering some pointers, give it this new pointer as well and
2481 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2482 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002483 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002484 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002485 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002486 // This window is already pilfering some pointers, and this new pointer is also
2487 // going to it. Therefore, take over this pointer and don't give it to anyone
2488 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002489 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002490 }
2491 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002492
2493 // Restrict all pilfered pointers to the pilfering windows.
2494 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 } else {
2496 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2497
2498 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002499 if (!tempTouchState.isDown(entry.deviceId) &&
2500 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002501 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2502 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2503 << " is not down or we previously dropped the pointer down event in "
2504 << "display " << displayId << ": " << entry.getDescription();
2505 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002506 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002507 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 }
2509
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002510 // If the pointer is not currently hovering, then ignore the event.
2511 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2512 const int32_t pointerId = entry.pointerProperties[0].id;
2513 if (oldState == nullptr ||
2514 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2515 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2516 "display "
2517 << displayId << ": " << entry.getDescription();
2518 outInjectionResult = InputEventInjectionResult::FAILED;
2519 return {};
2520 }
2521 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2522 }
2523
arthurhung6d4bed92021-03-17 11:59:33 +08002524 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002525
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002527 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002528 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002529 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002530 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002531 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002532 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002533 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002534 sp<WindowInfoHandle> newTouchedWindowHandle =
2535 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002536
Prabir Pradhan5735a322022-04-11 17:23:34 +00002537 // Verify targeted injection.
2538 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2539 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002540 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002541 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002542 }
2543
Vishnu Nair062a8672021-09-03 16:07:44 -07002544 // Drop touch events if requested by input feature
2545 if (newTouchedWindowHandle != nullptr &&
2546 shouldDropInput(entry, newTouchedWindowHandle)) {
2547 newTouchedWindowHandle = nullptr;
2548 }
2549
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002550 if (newTouchedWindowHandle != nullptr &&
2551 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002552 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002553 oldTouchedWindowHandle->getName().c_str(),
2554 newTouchedWindowHandle->getName().c_str(), displayId);
2555
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002557 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002558 const PointerProperties& pointer = entry.pointerProperties[0];
2559 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002560
2561 const TouchedWindow& touchedWindow =
2562 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002563 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002564 InputTarget::DispatchMode::SLIPPERY_EXIT,
2565 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002566 touchedWindow.getDownTimeInTarget(entry.deviceId),
2567 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
2569 // Make a slippery entrance into the new window.
2570 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002571 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002574 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002575 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002576 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002579 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002582 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002583 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002584 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
2586
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002587 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2588 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002589 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002590 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002591
2592 // Check if the wallpaper window should deliver the corresponding event.
2593 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002594 tempTouchState, entry.deviceId, pointer, targets);
2595 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002596 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598 }
Arthur Hung96483742022-11-15 03:30:48 +00002599
2600 // Update the pointerIds for non-splittable when it received pointer down.
2601 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2602 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002603 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002604 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2605 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002606 // Ignore drag window for it should just track one pointer.
2607 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2608 continue;
2609 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002610 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002611 }
2612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
2614
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002615 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002616 {
2617 std::vector<TouchedWindow> hoveringWindows =
2618 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2619 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002620 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002621 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2622 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002623 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002624 if (!target) {
2625 continue;
2626 }
2627 // Hardcode to single hovering pointer for now.
2628 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2629 pointerIds.set(entry.pointerProperties[0].id);
2630 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2631 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634
Prabir Pradhan5735a322022-04-11 17:23:34 +00002635 // Ensure that all touched windows are valid for injection.
2636 if (entry.injectionState != nullptr) {
2637 std::string errs;
2638 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002639 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2640 if (err) errs += "\n - " + *err;
2641 }
2642 if (!errs.empty()) {
2643 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002644 "%s:%s",
2645 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002646 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002647 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002648 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002649 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002650
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002651 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2652 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002654 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002655 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002656 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002657 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002658 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002659 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002660 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002661 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002662 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2663 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 }
2666 }
2667 }
2668 }
2669
Harry Cuttsb166c002023-05-09 13:06:05 +00002670 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2671 // only want the system UI to handle these gestures.
2672 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2673 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2674 if (isTouchpadNavGesture) {
2675 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2676 }
2677
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002678 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002679 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002680 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002681 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002682 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002683 continue;
2684 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002685 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002686 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002687 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002688 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002689
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002690 // During targeted injection, only allow owned targets to receive events
2691 std::erase_if(targets, [&](const InputTarget& target) {
2692 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2693 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2694 if (err) {
2695 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2696 << ": " << (*err);
2697 return true;
2698 }
2699 return false;
2700 });
2701
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002702 if (targets.empty()) {
2703 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2704 outInjectionResult = InputEventInjectionResult::FAILED;
2705 return {};
2706 }
2707
2708 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2709 // window that is actually receiving the entire gesture.
2710 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002711 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002712 })) {
2713 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2714 << entry.getDescription();
2715 outInjectionResult = InputEventInjectionResult::FAILED;
2716 return {};
2717 }
2718
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002719 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Prabir Pradhan502a7252023-12-01 16:11:24 +00002721 // Now that we have generated all of the input targets for this event, reset the dispatch
2722 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002723 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002724 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002725 }
2726
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002727 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002728 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002729 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002730 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002731 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002732 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002733 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002734 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2735 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002736 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2737 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2738 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
2740
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002741 // Save changes unless the action was scroll in which case the temporary touch
2742 // state was only valid for this one action.
2743 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002744 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002745 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002746 mTouchStatesByDisplay[displayId] = tempTouchState;
2747 } else {
2748 mTouchStatesByDisplay.erase(displayId);
2749 }
2750 }
2751
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002752 if (tempTouchState.windows.empty()) {
2753 mTouchStatesByDisplay.erase(displayId);
2754 }
2755
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002756 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757}
2758
arthurhung6d4bed92021-03-17 11:59:33 +08002759void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002760 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2761 // have an explicit reason to support it.
2762 constexpr bool isStylus = false;
2763
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002764 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002765 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002766 if (dropWindow) {
2767 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002768 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002769 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002770 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002771 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002772 }
2773 mDragState.reset();
2774}
2775
2776void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002777 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002778 return;
2779 }
2780
arthurhung6d4bed92021-03-17 11:59:33 +08002781 if (!mDragState->isStartDrag) {
2782 mDragState->isStartDrag = true;
2783 mDragState->isStylusButtonDownAtStart =
2784 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2785 }
2786
Arthur Hung54745652022-04-20 07:17:41 +00002787 // Find the pointer index by id.
2788 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002789 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002790 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2791 if (pointerProperties.id == mDragState->pointerId) {
2792 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002793 }
Arthur Hung54745652022-04-20 07:17:41 +00002794 }
arthurhung6d4bed92021-03-17 11:59:33 +08002795
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002796 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002797 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002798 }
2799
2800 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2801 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2802 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2803
2804 switch (maskedAction) {
2805 case AMOTION_EVENT_ACTION_MOVE: {
2806 // Handle the special case : stylus button no longer pressed.
2807 bool isStylusButtonDown =
2808 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2809 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2810 finishDragAndDrop(entry.displayId, x, y);
2811 return;
2812 }
2813
2814 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2815 // until we have an explicit reason to support it.
2816 constexpr bool isStylus = false;
2817
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002818 sp<WindowInfoHandle> hoverWindowHandle =
2819 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2820 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002821 // enqueue drag exit if needed.
2822 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2823 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2824 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002825 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002826 y);
2827 }
2828 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2829 }
2830 // enqueue drag location if needed.
2831 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002832 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002833 }
2834 break;
2835 }
2836
2837 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002838 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002839 break;
2840 }
2841 // The drag pointer is up.
2842 [[fallthrough]];
2843 case AMOTION_EVENT_ACTION_UP:
2844 finishDragAndDrop(entry.displayId, x, y);
2845 break;
2846 case AMOTION_EVENT_ACTION_CANCEL: {
2847 ALOGD("Receiving cancel when drag and drop.");
2848 sendDropWindowCommandLocked(nullptr, 0, 0);
2849 mDragState.reset();
2850 break;
2851 }
arthurhungb89ccb02020-12-30 16:19:01 +08002852 }
2853}
2854
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002855std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2856 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002857 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002859 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2860 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002861 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2862 return {};
2863 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002864 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002865 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002866 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867 inputTarget.flags = targetFlags;
2868 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2869 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2870 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2871 if (displayInfoIt != mDisplayInfos.end()) {
2872 inputTarget.displayTransform = displayInfoIt->second.transform;
2873 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002874 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002875 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2876 }
2877 return inputTarget;
2878}
2879
chaviw98318de2021-05-19 16:45:23 -05002880void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002881 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002882 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002883 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002884 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002885 std::vector<InputTarget>::iterator it =
2886 std::find_if(inputTargets.begin(), inputTargets.end(),
2887 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002888 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002889 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002890
chaviw98318de2021-05-19 16:45:23 -05002891 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002892
2893 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002894 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002895 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2896 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002897 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002898 return;
2899 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002900 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901 it = inputTargets.end() - 1;
2902 }
2903
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002904 if (it->flags != targetFlags) {
2905 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2906 }
2907 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2908 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2909 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2910 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002911}
2912
2913void InputDispatcher::addPointerWindowTargetLocked(
2914 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002915 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2916 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2917 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002918 if (pointerIds.none()) {
2919 for (const auto& target : inputTargets) {
2920 LOG(INFO) << "Target: " << target;
2921 }
2922 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2923 return;
2924 }
2925 std::vector<InputTarget>::iterator it =
2926 std::find_if(inputTargets.begin(), inputTargets.end(),
2927 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002928 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002929 });
2930
2931 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2932 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2933 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2934 // input targets for hovering pointers and for touching pointers.
2935 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2936 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002937 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002938 // Force the code below to create a new input target
2939 it = inputTargets.end();
2940 }
2941
2942 const WindowInfo* windowInfo = windowHandle->getInfo();
2943
2944 if (it == inputTargets.end()) {
2945 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002946 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2947 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002948 if (!target) {
2949 return;
2950 }
2951 inputTargets.push_back(*target);
2952 it = inputTargets.end() - 1;
2953 }
2954
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002955 if (it->dispatchMode != dispatchMode) {
2956 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2957 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2958 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002959 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002960 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2961 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002962 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002963 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002964 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002965 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2966 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002967
chaviw1ff3d1e2020-07-01 15:53:47 -07002968 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969}
2970
Michael Wright3dd60e22019-03-27 22:06:44 +00002971void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002972 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002973 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2974 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002975
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002976 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002977 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002978 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2979 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002980 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2981 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002982 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002983 target.setDefaultPointerTransform(target.displayTransform);
2984 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985 }
2986}
2987
Robert Carrc9bf1d32020-04-13 17:21:08 -07002988/**
2989 * Indicate whether one window handle should be considered as obscuring
2990 * another window handle. We only check a few preconditions. Actually
2991 * checking the bounds is left to the caller.
2992 */
chaviw98318de2021-05-19 16:45:23 -05002993static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2994 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002995 // Compare by token so cloned layers aren't counted
2996 if (haveSameToken(windowHandle, otherHandle)) {
2997 return false;
2998 }
2999 auto info = windowHandle->getInfo();
3000 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003001 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003002 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003003 } else if (otherInfo->alpha == 0 &&
3004 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003005 // Those act as if they were invisible, so we don't need to flag them.
3006 // We do want to potentially flag touchable windows even if they have 0
3007 // opacity, since they can consume touches and alter the effects of the
3008 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003009 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003010 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3011 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003012 } else if (info->ownerUid == otherInfo->ownerUid) {
3013 // If ownerUid is the same we don't generate occlusion events as there
3014 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003015 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003016 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003017 return false;
3018 } else if (otherInfo->displayId != info->displayId) {
3019 return false;
3020 }
3021 return true;
3022}
3023
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003024/**
3025 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3026 * untrusted, one should check:
3027 *
3028 * 1. If result.hasBlockingOcclusion is true.
3029 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3030 * BLOCK_UNTRUSTED.
3031 *
3032 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3033 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3034 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3035 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3036 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3037 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3038 *
3039 * If neither of those is true, then it means the touch can be allowed.
3040 */
3041InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003042 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3043 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003044 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003045 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003046 TouchOcclusionInfo info;
3047 info.hasBlockingOcclusion = false;
3048 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 info.obscuringUid = gui::Uid::INVALID;
3050 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003051 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003052 if (windowHandle == otherHandle) {
3053 break; // All future windows are below us. Exit early.
3054 }
chaviw98318de2021-05-19 16:45:23 -05003055 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003056 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3057 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003058 if (DEBUG_TOUCH_OCCLUSION) {
3059 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003060 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003061 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3063 // we perform the checks below to see if the touch can be propagated or not based on the
3064 // window's touch occlusion mode
3065 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3066 info.hasBlockingOcclusion = true;
3067 info.obscuringUid = otherInfo->ownerUid;
3068 info.obscuringPackage = otherInfo->packageName;
3069 break;
3070 }
3071 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003072 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003073 float opacity =
3074 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3075 // Given windows A and B:
3076 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3077 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3078 opacityByUid[uid] = opacity;
3079 if (opacity > info.obscuringOpacity) {
3080 info.obscuringOpacity = opacity;
3081 info.obscuringUid = uid;
3082 info.obscuringPackage = otherInfo->packageName;
3083 }
3084 }
3085 }
3086 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003087 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003088 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003089 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003090 return info;
3091}
3092
chaviw98318de2021-05-19 16:45:23 -05003093std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003094 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003095 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003096 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3097 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3098 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003099 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003100 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003101 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3102 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003103 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3104 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3105 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003106 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003107}
3108
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003109bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3110 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003111 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3112 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003113 return false;
3114 }
3115 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003116 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003117 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003118 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003119 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3120 return false;
3121 }
3122 return true;
3123}
3124
chaviw98318de2021-05-19 16:45:23 -05003125bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003128 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3129 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003130 if (windowHandle == otherHandle) {
3131 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
chaviw98318de2021-05-19 16:45:23 -05003133 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003134 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003135 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 return true;
3137 }
3138 }
3139 return false;
3140}
3141
chaviw98318de2021-05-19 16:45:23 -05003142bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003143 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003144 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3145 const WindowInfo* windowInfo = windowHandle->getInfo();
3146 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003147 if (windowHandle == otherHandle) {
3148 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003149 }
chaviw98318de2021-05-19 16:45:23 -05003150 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003151 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003152 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003153 return true;
3154 }
3155 }
3156 return false;
3157}
3158
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003159std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003160 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003161 if (applicationHandle != nullptr) {
3162 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003163 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 } else {
3165 return applicationHandle->getName();
3166 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003167 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003168 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
3172}
3173
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003174void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003175 if (!isUserActivityEvent(eventEntry)) {
3176 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003177 return;
3178 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003179
3180 const int32_t eventType = getUserActivityEventType(eventEntry);
3181 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3182 // Note that we're directly getting the time diff between the current event and the previous
3183 // event. This is assuming that the first user event always happens at a timestamp that is
3184 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3185 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3186 // value than the potential first user activity event time, so this is ok.
3187 std::chrono::nanoseconds timeSinceLastEvent =
3188 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3189 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3190 return;
3191 }
3192 }
3193
Tiger Huang721e26f2018-07-24 22:26:19 +08003194 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003195 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003196 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003197 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003198 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003199 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003200 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202 }
3203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003205 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3207 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 return;
3209 }
Josep del Riob3981622023-04-18 15:49:45 +00003210 if (windowDisablingUserActivityInfo != nullptr) {
3211 if (DEBUG_DISPATCH_CYCLE) {
3212 ALOGD("Not poking user activity: disabled by window '%s'.",
3213 windowDisablingUserActivityInfo->name.c_str());
3214 }
3215 return;
3216 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003219 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3221 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 return;
3223 }
Josep del Riob3981622023-04-18 15:49:45 +00003224 // If the key code is unknown, we don't consider it user activity
3225 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3226 return;
3227 }
3228 // Don't inhibit events that were intercepted or are not passed to
3229 // the apps, like system shortcuts
3230 if (windowDisablingUserActivityInfo != nullptr &&
3231 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3232 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3233 if (DEBUG_DISPATCH_CYCLE) {
3234 ALOGD("Not poking user activity: disabled by window '%s'.",
3235 windowDisablingUserActivityInfo->name.c_str());
3236 }
3237 return;
3238 }
3239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003242 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003243 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003244 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003245 break;
3246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
3248
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003249 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003250 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3251 REQUIRES(mLock) {
3252 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003253 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003254 };
3255 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256}
3257
3258void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003259 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003260 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003261 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003262 ATRACE_NAME_IF(ATRACE_ENABLED(),
3263 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3264 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003265 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003267 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003269 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003270 inputTarget.getPointerInfoString().c_str());
3271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 // Skip this event if the connection status is not normal.
3274 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003275 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003276 if (DEBUG_DISPATCH_CYCLE) {
3277 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003278 connection->getInputChannelName().c_str(),
3279 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 return;
3282 }
3283
3284 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003286 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003287 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003288 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003290 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003291 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003292 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3293 logDispatchStateLocked();
3294 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3295 "target on connection "
3296 << connection->getInputChannelName() << " for "
3297 << originalMotionEntry.getDescription();
3298 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003300 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003301 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 if (!splitMotionEntry) {
3303 return; // split event was dropped
3304 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003305 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3306 std::string reason = std::string("reason=pointer cancel on split window");
3307 android_log_event_list(LOGTAG_INPUT_CANCEL)
3308 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3309 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003310 if (DEBUG_FOCUS) {
3311 ALOGD("channel '%s' ~ Split motion event.",
3312 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003313 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003314 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003315 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3316 std::move(splitMotionEntry),
3317 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 return;
3319 }
3320 }
3321
3322 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003323 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3324 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325}
3326
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003327void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3328 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3329 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003330 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003331 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3332 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003333 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003334
hongzuo liu95785e22022-09-06 02:51:35 +00003335 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003337 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
3339 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003340 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 startDispatchCycleLocked(currentTime, connection);
3342 }
3343}
3344
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003345void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003346 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003347 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003348 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3349 eventEntry->type == EventEntry::Type::MOTION;
3350 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3351 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3352 << inputTarget << " connection: " << connection->getInputChannelName()
3353 << " entry: " << eventEntry->getDescription();
3354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 // This is a new event.
3356 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003357 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003358 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003360 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3361 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003362 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003364 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003365 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003366 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3367 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003368 LOG(WARNING) << "channel " << connection->getInputChannelName()
3369 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 return; // skip the inconsistent event
3371 }
3372 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003375 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003376 std::shared_ptr<const MotionEntry> resolvedMotion =
3377 std::static_pointer_cast<const MotionEntry>(eventEntry);
3378 {
3379 // Determine the resolved motion entry.
3380 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3381 int32_t resolvedAction = motionEntry.action;
3382 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003384 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003385 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003386 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003387 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003388 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003389 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003390 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003391 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003392 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003393 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3394 }
3395 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3396 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3397 motionEntry.displayId)) {
3398 if (DEBUG_DISPATCH_CYCLE) {
3399 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3400 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3401 "enter event";
3402 }
3403 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3404 }
3405
3406 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3407 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3408 }
3409 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3410 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3411 }
3412 if (dispatchEntry->targetFlags.test(
3413 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3414 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3415 }
3416
3417 dispatchEntry->resolvedFlags = resolvedFlags;
3418 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003419 std::optional<std::vector<PointerProperties>> usingProperties;
3420 std::optional<std::vector<PointerCoords>> usingCoords;
3421 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3422 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3423 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3424 // the dispatcher, and therefore the coordinates of this event are currently
3425 // incorrect. These events should use the coordinates of the last dispatched
3426 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3427 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3428 std::optional<std::pair<std::vector<PointerProperties>,
3429 std::vector<PointerCoords>>>
3430 pointerInfo =
3431 connection->inputState.getPointersOfLastEvent(motionEntry,
3432 hovering);
3433 if (pointerInfo) {
3434 usingProperties = pointerInfo->first;
3435 usingCoords = pointerInfo->second;
3436 }
3437 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003438 // Generate a new MotionEntry with a new eventId using the resolved action and
3439 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003440 resolvedMotion = std::make_shared<
3441 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3442 motionEntry.eventTime, motionEntry.deviceId,
3443 motionEntry.source, motionEntry.displayId,
3444 motionEntry.policyFlags, resolvedAction,
3445 motionEntry.actionButton, resolvedFlags,
3446 motionEntry.metaState, motionEntry.buttonState,
3447 motionEntry.classification, motionEntry.edgeFlags,
3448 motionEntry.xPrecision, motionEntry.yPrecision,
3449 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3450 motionEntry.downTime,
3451 usingProperties.value_or(motionEntry.pointerProperties),
3452 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003453 if (ATRACE_ENABLED()) {
3454 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3455 ") to MotionEvent(id=0x%" PRIx32 ").",
3456 motionEntry.id, resolvedMotion->id);
3457 ATRACE_NAME(message.c_str());
3458 }
3459
3460 // Set the resolved motion entry in the DispatchEntry.
3461 dispatchEntry->eventEntry = resolvedMotion;
3462 eventEntry = resolvedMotion;
3463 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003466 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3467 // devices being active at the same time in the same window, so if a new device is
3468 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003469 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003470 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003471 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003472 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003473 << connection->getInputChannelName() << " with event "
3474 << cancelEvent->getDescription();
3475 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3476 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003477 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003478
3479 // Send these cancel events to the queue before sending the event from the new
3480 // device.
3481 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3482 }
3483
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003484 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003486 LOG(WARNING) << "channel " << connection->getInputChannelName()
3487 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 return; // skip the inconsistent event
3489 }
3490
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003491 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3492 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003493 // Skip reporting pointer down outside focus to the policy.
3494 break;
3495 }
3496
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003497 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003498 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499
3500 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003502 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003503 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003504 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3505 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003506 break;
3507 }
Chris Yef59a2f42020-10-16 12:55:26 -07003508 case EventEntry::Type::SENSOR: {
3509 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3510 break;
3511 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003512 case EventEntry::Type::CONFIGURATION_CHANGED:
3513 case EventEntry::Type::DEVICE_RESET: {
3514 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003515 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003516 break;
3517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519
3520 // Remember that we are waiting for this dispatch to complete.
3521 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003522 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524
3525 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003526 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003527 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003528}
3529
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003530/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003531 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003532 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003533 * The first role is to log input interaction with windows, which helps determine what the user was
3534 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3535 * that user started interacting with launcher window, as well as any other window that received
3536 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3537 * when the set of tokens that received the event changes. It is not logged again as long as the
3538 * user is interacting with the same windows.
3539 *
3540 * The second role is to track input device activity for metrics collection. For each input event,
3541 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3542 * input_interaction logs, the device interaction is reported even when the set of interaction
3543 * tokens do not change.
3544 *
3545 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3546 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003547 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003548void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3549 const std::vector<InputTarget>& targets) {
3550 int32_t deviceId;
3551 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003552 // Skip ACTION_UP events, and all events other than keys and motions
3553 if (entry.type == EventEntry::Type::KEY) {
3554 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3555 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3556 return;
3557 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003558 deviceId = keyEntry.deviceId;
3559 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003560 } else if (entry.type == EventEntry::Type::MOTION) {
3561 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3562 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003563 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3564 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003565 return;
3566 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003567 deviceId = motionEntry.deviceId;
3568 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003569 } else {
3570 return; // Not a key or a motion
3571 }
3572
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003573 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003574 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003575 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003576 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003577 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003578 continue; // Skip windows that receive ACTION_OUTSIDE
3579 }
3580
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003581 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003582 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003583 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003584 if (target.windowHandle) {
3585 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3586 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003587 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003588
3589 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3590 REQUIRES(mLock) {
3591 scoped_unlock unlock(mLock);
3592 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3593 };
3594 postCommandLocked(std::move(command));
3595
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003596 if (newConnectionTokens == mInteractionConnectionTokens) {
3597 return; // no change
3598 }
3599 mInteractionConnectionTokens = newConnectionTokens;
3600
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003601 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003602 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003603 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003604 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003605 std::string message = "Interaction with: " + targetList;
3606 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003607 message += "<none>";
3608 }
3609 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3610}
3611
chaviwfd6d3512019-03-25 13:23:49 -07003612void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003613 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003614 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003615 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3616 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003617 return;
3618 }
3619
Vishnu Nairc519ff72021-01-21 08:23:08 -08003620 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003621 if (focusedToken == token) {
3622 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003623 return;
3624 }
3625
Prabir Pradhancef936d2021-07-21 16:17:52 +00003626 auto command = [this, token]() REQUIRES(mLock) {
3627 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003628 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003629 };
3630 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631}
3632
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003633status_t InputDispatcher::publishMotionEvent(Connection& connection,
3634 DispatchEntry& dispatchEntry) const {
3635 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3636 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3637
3638 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003639 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003640
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003641 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003642 // Set the X and Y offset and X and Y scale depending on the input source.
3643 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003644 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003645 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3646 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003647 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003648 scaledCoords[i] = motionEntry.pointerCoords[i];
3649 // Don't apply window scale here since we don't want scale to affect raw
3650 // coordinates. The scale will be sent back to the client and applied
3651 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003652 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003653 }
3654 usingCoords = scaledCoords;
3655 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003656 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003657 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003658 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003659 scaledCoords[i].clear();
3660 }
3661 usingCoords = scaledCoords;
3662 }
3663
3664 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3665
3666 // Publish the motion event.
3667 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003668 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3669 motionEntry.source, motionEntry.displayId, std::move(hmac),
3670 motionEntry.action, motionEntry.actionButton,
3671 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3672 motionEntry.metaState, motionEntry.buttonState,
3673 motionEntry.classification, dispatchEntry.transform,
3674 motionEntry.xPrecision, motionEntry.yPrecision,
3675 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3676 dispatchEntry.rawTransform, motionEntry.downTime,
3677 motionEntry.eventTime, motionEntry.getPointerCount(),
3678 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003679}
3680
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003682 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003683 ATRACE_NAME_IF(ATRACE_ENABLED(),
3684 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3685 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003686 if (DEBUG_DISPATCH_CYCLE) {
3687 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003690 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003691 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003693 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003694 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695
3696 // Publish the event.
3697 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003698 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3699 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003700 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003701 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3702 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003703 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003704 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3705 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003708 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003709 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003710 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3711 keyEntry.deviceId, keyEntry.source,
3712 keyEntry.displayId, std::move(hmac),
3713 keyEntry.action, dispatchEntry->resolvedFlags,
3714 keyEntry.keyCode, keyEntry.scanCode,
3715 keyEntry.metaState, keyEntry.repeatCount,
3716 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003717 if (mTracer) {
3718 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3719 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003720 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003723 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003724 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003725 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3726 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003727 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003728 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003729 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003730 if (mTracer) {
3731 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3732 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 break;
3734 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003735
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003736 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003737 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003738 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003739 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003740 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003741 break;
3742 }
3743
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003744 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3745 const TouchModeEntry& touchModeEntry =
3746 static_cast<const TouchModeEntry&>(eventEntry);
3747 status = connection->inputPublisher
3748 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3749 touchModeEntry.inTouchMode);
3750
3751 break;
3752 }
3753
Prabir Pradhan99987712020-11-10 18:43:05 -08003754 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3755 const auto& captureEntry =
3756 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3757 status = connection->inputPublisher
3758 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003759 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003760 break;
3761 }
3762
arthurhungb89ccb02020-12-30 16:19:01 +08003763 case EventEntry::Type::DRAG: {
3764 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3765 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3766 dragEntry.id, dragEntry.x,
3767 dragEntry.y,
3768 dragEntry.isExiting);
3769 break;
3770 }
3771
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003772 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003773 case EventEntry::Type::DEVICE_RESET:
3774 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003775 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003776 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 }
3780
3781 // Check the result.
3782 if (status) {
3783 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003784 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 "This is unexpected because the wait queue is empty, so the pipe "
3787 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003788 "event to it, status=%s(%d)",
3789 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3790 status);
Harry Cutts33476232023-01-30 19:57:29 +00003791 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 } else {
3793 // Pipe is full and we are waiting for the app to finish process some events
3794 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003795 if (DEBUG_DISPATCH_CYCLE) {
3796 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3797 "waiting for the application to catch up",
3798 connection->getInputChannelName().c_str());
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
3801 } else {
3802 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003803 "status=%s(%d)",
3804 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3805 status);
Harry Cutts33476232023-01-30 19:57:29 +00003806 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808 return;
3809 }
3810
3811 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003812 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3813 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3814 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003815 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003816 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003817 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003818 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003819 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821}
3822
chaviw09c8d2d2020-08-24 15:48:26 -07003823std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3824 size_t size;
3825 switch (event.type) {
3826 case VerifiedInputEvent::Type::KEY: {
3827 size = sizeof(VerifiedKeyEvent);
3828 break;
3829 }
3830 case VerifiedInputEvent::Type::MOTION: {
3831 size = sizeof(VerifiedMotionEvent);
3832 break;
3833 }
3834 }
3835 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3836 return mHmacKeyManager.sign(start, size);
3837}
3838
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003839const std::array<uint8_t, 32> InputDispatcher::getSignature(
3840 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003841 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003842 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003843 // Only sign events up and down events as the purely move events
3844 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003845 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003846 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003847
3848 VerifiedMotionEvent verifiedEvent =
3849 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3850 verifiedEvent.actionMasked = actionMasked;
3851 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3852 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003853}
3854
3855const std::array<uint8_t, 32> InputDispatcher::getSignature(
3856 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3857 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3858 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003859 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003860}
3861
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003863 const std::shared_ptr<Connection>& connection,
3864 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003865 if (DEBUG_DISPATCH_CYCLE) {
3866 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3867 connection->getInputChannelName().c_str(), seq, toString(handled));
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003870 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 return;
3872 }
3873
3874 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003875 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3876 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3877 };
3878 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879}
3880
3881void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003882 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003883 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003884 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003885 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3886 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
3889 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003890 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003891 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003892 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003893 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
3895 // The connection appears to be unrecoverably broken.
3896 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003897 if (connection->status == Connection::Status::NORMAL) {
3898 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899
3900 if (notify) {
3901 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003902 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3903 connection->getInputChannelName().c_str());
3904
3905 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003906 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003907 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003908 };
3909 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 }
3911 }
3912}
3913
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003914void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003915 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003916 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003917 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 }
3919}
3920
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003921void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003923 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925}
3926
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003927int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3928 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003929 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003930 if (connection == nullptr) {
3931 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3932 connectionToken.get(), events);
3933 return 0; // remove the callback
3934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003936 bool notify;
3937 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3938 if (!(events & ALOOPER_EVENT_INPUT)) {
3939 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3940 "events=0x%x",
3941 connection->getInputChannelName().c_str(), events);
3942 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003945 nsecs_t currentTime = now();
3946 bool gotOne = false;
3947 status_t status = OK;
3948 for (;;) {
3949 Result<InputPublisher::ConsumerResponse> result =
3950 connection->inputPublisher.receiveConsumerResponse();
3951 if (!result.ok()) {
3952 status = result.error().code();
3953 break;
3954 }
3955
3956 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3957 const InputPublisher::Finished& finish =
3958 std::get<InputPublisher::Finished>(*result);
3959 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3960 finish.consumeTime);
3961 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003962 if (shouldReportMetricsForConnection(*connection)) {
3963 const InputPublisher::Timeline& timeline =
3964 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003965 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3966 connection->getToken(),
3967 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003968 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003969 }
3970 gotOne = true;
3971 }
3972 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003973 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003974 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 return 1;
3976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 }
3978
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003979 notify = status != DEAD_OBJECT || !connection->monitor;
3980 if (notify) {
3981 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3982 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3983 status);
3984 }
3985 } else {
3986 // Monitor channels are never explicitly unregistered.
3987 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003988 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003989 notify = !connection->monitor && stillHaveWindowHandle;
3990 if (notify) {
3991 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3992 connection->getInputChannelName().c_str(), events);
3993 }
3994 }
3995
3996 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003997 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003998 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999}
4000
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004003 // Cancel windows (i.e. non-monitors).
4004 // A channel must have at least one window to receive any input. If a window was removed, the
4005 // event streams directed to the window will already have been canceled during window removal.
4006 // So there is no need to generate cancellations for connections without any windows.
4007 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4008 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4009 // through a non-touched window if there are more than one window for an input channel.
4010 if (cancelPointers) {
4011 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4012 if (options.displayId.has_value() && options.displayId != displayId) {
4013 continue;
4014 }
4015 for (const auto& touchedWindow : touchState.windows) {
4016 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4017 }
4018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004020 // Follow up by generating cancellations for all windows, because we don't explicitly track
4021 // the windows that have an ongoing focus event stream.
4022 if (cancelNonPointers) {
4023 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4024 for (const auto& windowHandle : handles) {
4025 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4026 }
4027 }
4028 }
4029
4030 // Cancel monitors.
4031 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032}
4033
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004034void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004035 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004036 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004037 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004038 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4039 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004040 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004041 }
4042}
4043
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004044void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4045 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4046 const std::shared_ptr<Connection>& connection) {
4047 if (windowHandle == nullptr) {
4048 LOG(FATAL) << __func__ << ": Window handle must not be null";
4049 }
4050 if (connection) {
4051 // The connection can be optionally provided to avoid multiple lookups.
4052 if (windowHandle->getToken() != connection->getToken()) {
4053 LOG(FATAL) << __func__
4054 << ": Wrong connection provided for window: " << windowHandle->getName();
4055 }
4056 }
4057
4058 std::shared_ptr<Connection> resolvedConnection =
4059 connection ? connection : getConnectionLocked(windowHandle->getToken());
4060 if (!resolvedConnection) {
4061 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4062 return;
4063 }
4064 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4065}
4066
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004068 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4069 const sp<WindowInfoHandle>& window) {
4070 if (!connection->monitor && window == nullptr) {
4071 LOG(FATAL) << __func__
4072 << ": Cannot send event to non-monitor channel without a window - channel: "
4073 << connection->getInputChannelName();
4074 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004075 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 return;
4077 }
4078
4079 nsecs_t currentTime = now();
4080
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004082 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004084 if (cancelationEvents.empty()) {
4085 return;
4086 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004087
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004088 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4089 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004090 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004091 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004092 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004094
Arthur Hungb3307ee2021-10-14 10:57:37 +00004095 std::string reason = std::string("reason=").append(options.reason);
4096 android_log_event_list(LOGTAG_INPUT_CANCEL)
4097 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4098
hongzuo liu95785e22022-09-06 02:51:35 +00004099 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004100 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004101 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004102 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004103
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004104 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004105 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004106 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004107
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004108 switch (cancelationEventEntry->type) {
4109 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004110 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004111 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004112 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4113 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004114 } else {
4115 targets.emplace_back(fallbackTarget);
4116 }
4117 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004118 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004120 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004121 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004122 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004123 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004124 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004125 pointerIndex++) {
4126 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4127 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004128 if (mDragState && mDragState->dragWindow->getToken() == token &&
4129 pointerIds.test(mDragState->pointerId)) {
4130 LOG(INFO) << __func__
4131 << ": Canceling drag and drop because the pointers for the drag "
4132 "window are being canceled.";
4133 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4134 mDragState.reset();
4135 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004136 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4137 ftl::Flags<InputTarget::Flags>(), pointerIds,
4138 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004139 } else {
4140 targets.emplace_back(fallbackTarget);
4141 const auto it = mDisplayInfos.find(motionEntry.displayId);
4142 if (it != mDisplayInfos.end()) {
4143 targets.back().displayTransform = it->second.transform;
4144 targets.back().setDefaultPointerTransform(it->second.transform);
4145 }
4146 }
4147 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004148 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004150 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004151 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004152 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4153 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004154 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004155 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004156 break;
4157 }
4158 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004159 case EventEntry::Type::DEVICE_RESET:
4160 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004161 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004162 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004163 break;
4164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 }
4166
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004167 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004168 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004170
hongzuo liu95785e22022-09-06 02:51:35 +00004171 // If the outbound queue was previously empty, start the dispatch cycle going.
4172 if (wasEmpty && !connection->outboundQueue.empty()) {
4173 startDispatchCycleLocked(currentTime, connection);
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175}
4176
Svet Ganov5d3bc372020-01-26 23:11:07 -08004177void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004178 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004179 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004180 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004181 return;
4182 }
4183
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004185 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186
4187 if (downEvents.empty()) {
4188 return;
4189 }
4190
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004191 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004192 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4193 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004194 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004196 const auto [_, touchedWindowState, displayId] =
4197 findTouchStateWindowAndDisplayLocked(connection->getToken());
4198 if (touchedWindowState == nullptr) {
4199 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4200 }
4201 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004202
hongzuo liu95785e22022-09-06 02:51:35 +00004203 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004204 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004205 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004206 switch (downEventEntry->type) {
4207 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004208 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4209 if (windowHandle != nullptr) {
4210 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004211 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004212 pointerIndex++) {
4213 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4214 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004215 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4216 targetFlags, pointerIds, motionEntry.downTime,
4217 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004218 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004219 targets.emplace_back(connection, 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