blob: 9d744f6d5863e2f1b0b76069bfae5f8420a43abb [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058#define INDENT " "
59#define INDENT2 " "
60#define INDENT3 " "
61#define INDENT4 " "
62
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080063using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070064using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080065using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000066using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070068using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050069using android::gui::FocusRequest;
70using android::gui::TouchOcclusionMode;
71using android::gui::WindowInfo;
72using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080073using android::os::InputEventInjectionResult;
74using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000075namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Prabir Pradhancef936d2021-07-21 16:17:52 +000079namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000080
Prabir Pradhandae52792023-12-15 07:36:40 +000081// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
82// flag is enabled. When the flag is changed, tracing will only be available after reboot.
83bool isInputTracingEnabled() {
84 static const std::string buildType = base::GetProperty("ro.build.type", "user");
85 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
86 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
87}
88
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000089template <class Entry>
90void ensureEventTraced(const Entry& entry) {
91 if (!entry.traceTracker) {
92 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
93 }
94}
95
Prabir Pradhancef936d2021-07-21 16:17:52 +000096// Temporarily releases a held mutex for the lifetime of the instance.
97// Named to match std::scoped_lock
98class scoped_unlock {
99public:
100 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
101 ~scoped_unlock() { mMutex.lock(); }
102
103private:
104 std::mutex& mMutex;
105};
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Default input dispatching timeout if there is no focused application or paused window
108// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800109const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
110 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
111 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800113// The default minimum time gap between two user activity poke events.
114const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
115
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800116const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
120
121// Log a warning when an interception call takes longer than this to process.
122constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123
124// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000125constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
126
Antonio Kantekea47acb2021-12-23 12:41:25 -0800127// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000128constexpr int LOGTAG_INPUT_INTERACTION = 62000;
129constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000130constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000131
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000132const ui::Transform kIdentityTransform;
133
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000134inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 return systemTime(SYSTEM_TIME_MONOTONIC);
136}
137
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700138inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000139 if (binder == nullptr) {
140 return "<null>";
141 }
142 return StringPrintf("%p", binder.get());
143}
144
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000145static std::string uidString(const gui::Uid& uid) {
146 return uid.toString();
147}
148
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700149Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700151 case AKEY_EVENT_ACTION_DOWN:
152 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700153 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700154 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700155 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157}
158
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159Result<void> validateKeyEvent(int32_t action) {
160 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161}
162
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800164 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_UP: {
167 if (pointerCount != 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
176 if (pointerCount < 1) {
177 return Error() << "invalid pointer count " << pointerCount;
178 }
179 return {};
180 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800181 case AMOTION_EVENT_ACTION_CANCEL:
182 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700184 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_POINTER_DOWN:
186 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800187 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700188 if (index < 0) {
189 return Error() << "invalid index " << index << " for "
190 << MotionEvent::actionToString(action);
191 }
192 if (index >= pointerCount) {
193 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
194 }
195 if (pointerCount <= 1) {
196 return Error() << "invalid pointer count " << pointerCount << " for "
197 << MotionEvent::actionToString(action);
198 }
199 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 }
201 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700202 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
203 if (actionButton == 0) {
204 return Error() << "action button should be nonzero for "
205 << MotionEvent::actionToString(action);
206 }
207 return {};
208 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700209 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700210 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212}
213
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000214int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500215 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
216}
217
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
219 const PointerProperties* pointerProperties) {
220 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
221 if (!actionCheck.ok()) {
222 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer count " << pointerCount
226 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 for (size_t i = 0; i < pointerCount; i++) {
230 int32_t id = pointerProperties[i].id;
231 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700232 return Error() << "Motion event has invalid pointer id " << id
233 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800235 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700236 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800238 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return {};
241}
242
243Result<void> validateInputEvent(const InputEvent& event) {
244 switch (event.getType()) {
245 case InputEventType::KEY: {
246 const KeyEvent& key = static_cast<const KeyEvent&>(event);
247 const int32_t action = key.getAction();
248 return validateKeyEvent(action);
249 }
250 case InputEventType::MOTION: {
251 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
252 const int32_t action = motion.getAction();
253 const size_t pointerCount = motion.getPointerCount();
254 const PointerProperties* pointerProperties = motion.getPointerProperties();
255 const int32_t actionButton = motion.getActionButton();
256 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
257 }
258 default: {
259 return {};
260 }
261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262}
263
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800264std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
265 std::bitset<MAX_POINTER_ID + 1> pointerIds;
266 for (const PointerProperties& pointer : pointers) {
267 pointerIds.set(pointer.id);
268 }
269 return pointerIds;
270}
271
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000274 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 }
276
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000277 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 bool first = true;
279 Region::const_iterator cur = region.begin();
280 Region::const_iterator const tail = region.end();
281 while (cur != tail) {
282 if (first) {
283 first = false;
284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800285 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800287 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 cur++;
289 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000290 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291}
292
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000293std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
294 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500295 constexpr size_t maxEntries = 50; // max events to print
296 constexpr size_t skipBegin = maxEntries / 2;
297 const size_t skipEnd = queue.size() - maxEntries / 2;
298 // skip from maxEntries / 2 ... size() - maxEntries/2
299 // only print from 0 .. skipBegin and then from skipEnd .. size()
300
301 std::string dump;
302 for (size_t i = 0; i < queue.size(); i++) {
303 const DispatchEntry& entry = *queue[i];
304 if (i >= skipBegin && i < skipEnd) {
305 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
306 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
307 continue;
308 }
309 dump.append(INDENT4);
310 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000311 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
312 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500313 ns2ms(currentTime - entry.eventEntry->eventTime));
314 if (entry.deliveryTime != 0) {
315 // This entry was delivered, so add information on how long we've been waiting
316 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
317 }
318 dump.append("\n");
319 }
320 return dump;
321}
322
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700323/**
324 * Find the entry in std::unordered_map by key, and return it.
325 * If the entry is not found, return a default constructed entry.
326 *
327 * Useful when the entries are vectors, since an empty vector will be returned
328 * if the entry is not found.
329 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
330 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700331template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700334 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800335}
336
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700338 if (first == second) {
339 return true;
340 }
341
342 if (first == nullptr || second == nullptr) {
343 return false;
344 }
345
346 return first->getToken() == second->getToken();
347}
348
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000349bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000350 if (first == nullptr || second == nullptr) {
351 return false;
352 }
353 return first->applicationInfo.token != nullptr &&
354 first->applicationInfo.token == second->applicationInfo.token;
355}
356
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800357template <typename T>
358size_t firstMarkedBit(T set) {
359 // TODO: replace with std::countr_zero from <bit> when that's available
360 LOG_ALWAYS_FATAL_IF(set.none());
361 size_t i = 0;
362 while (!set.test(i)) {
363 i++;
364 }
365 return i;
366}
367
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000368std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
369 std::shared_ptr<const EventEntry> eventEntry,
370 ftl::Flags<InputTarget::Flags> inputTargetFlags,
371 int64_t vsyncId) {
372 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
373 const std::optional<int32_t> windowId =
374 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
375 // Assume the only targets that are not associated with a window are global monitors, and use
376 // the system UID for global monitors for tracing purposes.
377 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 if (inputTarget.useDefaultPointerTransform()) {
379 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700380 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700381 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000382 inputTarget.globalScaleFactor, uid, vsyncId,
383 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000384 }
385
386 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
387 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700390 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000391
392 // Use the first pointer information to normalize all other pointers. This could be any pointer
393 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700394 // uses the transform for the normalized pointer.
395 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800396 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700397 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398
399 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700400 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
402 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700403 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404
405 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700406 // First, apply the current pointer's transform to update the coordinates into
407 // window space.
408 pointerCoords[pointerIndex].transform(currTransform);
409 // Next, apply the inverse transform of the normalized coordinates so the
410 // current coordinates are transformed into the normalized coordinate space.
411 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412 }
413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700414 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000415 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
416 motionEntry.eventTime, motionEntry.deviceId,
417 motionEntry.source, motionEntry.displayId,
418 motionEntry.policyFlags, motionEntry.action,
419 motionEntry.actionButton, motionEntry.flags,
420 motionEntry.metaState, motionEntry.buttonState,
421 motionEntry.classification, motionEntry.edgeFlags,
422 motionEntry.xPrecision, motionEntry.yPrecision,
423 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
424 motionEntry.downTime, motionEntry.pointerProperties,
425 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000426
427 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700428 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700429 firstPointerTransform, inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000430 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431 return dispatchEntry;
432}
433
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500434template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500436 if (lhs == nullptr && rhs == nullptr) {
437 return true;
438 }
439 if (lhs == nullptr || rhs == nullptr) {
440 return false;
441 }
442 return *lhs == *rhs;
443}
444
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000445KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000446 KeyEvent event;
447 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
448 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
449 entry.repeatCount, entry.downTime, entry.eventTime);
450 return event;
451}
452
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000454 // Do not keep track of gesture monitors. They receive every event and would disproportionately
455 // affect the statistics.
456 if (connection.monitor) {
457 return false;
458 }
459 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
460 if (!connection.responsive) {
461 return false;
462 }
463 return true;
464}
465
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000466bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000467 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
468 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000469 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
470 return false;
471 }
472 // Only track latency for events that originated from hardware
473 if (eventEntry.isSynthesized()) {
474 return false;
475 }
476 const EventEntry::Type& inputEventEntryType = eventEntry.type;
477 if (inputEventEntryType == EventEntry::Type::KEY) {
478 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
479 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
480 return false;
481 }
482 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
483 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
484 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
485 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
486 return false;
487 }
488 } else {
489 // Not a key or a motion
490 return false;
491 }
492 if (!shouldReportMetricsForConnection(connection)) {
493 return false;
494 }
495 return true;
496}
497
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498/**
499 * Connection is responsive if it has no events in the waitQueue that are older than the
500 * current time.
501 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000502bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000503 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000504 for (const auto& dispatchEntry : connection.waitQueue) {
505 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000506 return false;
507 }
508 }
509 return true;
510}
511
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512// Returns true if the event type passed as argument represents a user activity.
513bool isUserActivityEvent(const EventEntry& eventEntry) {
514 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000515 case EventEntry::Type::CONFIGURATION_CHANGED:
516 case EventEntry::Type::DEVICE_RESET:
517 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::FOCUS:
519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000520 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000521 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000522 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000523 case EventEntry::Type::KEY:
524 case EventEntry::Type::MOTION:
525 return true;
526 }
527}
528
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000530bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000531 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800532 const auto inputConfig = windowInfo.inputConfig;
533 if (windowInfo.displayId != displayId ||
534 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800535 return false;
536 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700537 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800538 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800539 return false;
540 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000541
542 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
543 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
544 // the window. Points on the right and bottom edges should not be inside the window, so we need
545 // to be careful about performing a hit test when the display is rotated, since the "right" and
546 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
547 // logical display in which WM determined the bounds. Perform the hit test in the logical
548 // display space to ensure these edges are considered correctly in all orientations.
549 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
550 const auto p = displayTransform.transform(x, y);
551 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800552 return false;
553 }
554 return true;
555}
556
Prabir Pradhand65552b2021-10-07 11:23:50 -0700557bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
558 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000559 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700560}
561
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800562// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000563// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
564// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
565// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800566// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000567bool canReceiveForegroundTouches(const WindowInfo& info) {
568 // A non-touchable window can still receive touch events (e.g. in the case of
569 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
570 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
571}
572
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000573bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700574 if (windowHandle == nullptr) {
575 return false;
576 }
577 const WindowInfo* windowInfo = windowHandle->getInfo();
578 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
579 return true;
580 }
581 return false;
582}
583
Prabir Pradhan5735a322022-04-11 17:23:34 +0000584// Checks targeted injection using the window's owner's uid.
585// Returns an empty string if an entry can be sent to the given window, or an error message if the
586// entry is a targeted injection whose uid target doesn't match the window owner.
587std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
588 const EventEntry& entry) {
589 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
590 // The event was not injected, or the injected event does not target a window.
591 return {};
592 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000593 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000594 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000595 return StringPrintf("No valid window target for injection into uid %s.",
596 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000597 }
598 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000599 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
600 "owned by uid %s.",
601 uid.toString().c_str(), window->getName().c_str(),
602 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000603 }
604 return {};
605}
606
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000607std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700608 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
609 // Always dispatch mouse events to cursor position.
610 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000611 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612 }
613
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700614 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000615 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
616 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700617}
618
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700619std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
620 if (eventEntry.type == EventEntry::Type::KEY) {
621 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
622 return keyEntry.downTime;
623 } else if (eventEntry.type == EventEntry::Type::MOTION) {
624 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
625 return motionEntry.downTime;
626 }
627 return std::nullopt;
628}
629
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000630/**
631 * Compare the old touch state to the new touch state, and generate the corresponding touched
632 * windows (== input targets).
633 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
634 * If the pointer just entered the new window, produce HOVER_ENTER.
635 * For pointers remaining in the window, produce HOVER_MOVE.
636 */
637std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
638 const TouchState& newTouchState,
639 const MotionEntry& entry) {
640 std::vector<TouchedWindow> out;
641 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700642
643 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
644 // ACTION_SCROLL events should not affect the hovering pointer dispatch
645 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000646 }
647
648 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800649 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000650
651 std::set<sp<WindowInfoHandle>> oldWindows;
652 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800653 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000654 }
655
656 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800657 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000658
659 // If the pointer is no longer in the new window set, send HOVER_EXIT.
660 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
661 if (newWindows.find(oldWindow) == newWindows.end()) {
662 TouchedWindow touchedWindow;
663 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000664 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000665 out.push_back(touchedWindow);
666 }
667 }
668
669 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
670 TouchedWindow touchedWindow;
671 touchedWindow.windowHandle = newWindow;
672 if (oldWindows.find(newWindow) == oldWindows.end()) {
673 // Any windows that have this pointer now, and didn't have it before, should get
674 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000675 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000676 } else {
677 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700678 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700679 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000680 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
681 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700682 // The Accessibility injected touch exploration event stream
683 // has known inconsistencies, so log ERROR instead of
684 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700685 severity = android::base::LogSeverity::ERROR;
686 }
687 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700688 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000689 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000690 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800691 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000692 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
693 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
694 }
695 out.push_back(touchedWindow);
696 }
697 return out;
698}
699
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800700template <typename T>
701std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
702 left.insert(left.end(), right.begin(), right.end());
703 return left;
704}
705
Harry Cuttsb166c002023-05-09 13:06:05 +0000706// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
707// both.
708void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
709 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
710 if (!window.windowHandle->getInfo()->inputConfig.test(
711 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
712 // In addition to TouchState, erase this window from the input targets! We don't have a
713 // good way to do this today except by adding a nested loop.
714 // TODO(b/282025641): simplify this code once InputTargets are being identified
715 // separately from TouchedWindows.
716 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800717 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000718 });
719 return true;
720 }
721 return false;
722 });
723}
724
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700725/**
726 * In general, touch should be always split between windows. Some exceptions:
727 * 1. Don't split touch if all of the below is true:
728 * (a) we have an active pointer down *and*
729 * (b) a new pointer is going down that's from the same device *and*
730 * (c) the window that's receiving the current pointer does not support split touch.
731 * 2. Don't split mouse events
732 */
733bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
734 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
735 // We should never split mouse events
736 return false;
737 }
738 for (const TouchedWindow& touchedWindow : touchState.windows) {
739 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
740 // Spy windows should not affect whether or not touch is split.
741 continue;
742 }
743 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
744 continue;
745 }
746 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
747 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
748 // Wallpaper window should not affect whether or not touch is split
749 continue;
750 }
751
752 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
753 return false;
754 }
755 }
756 return true;
757}
758
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700759/**
760 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
761 */
762bool isStylusActiveInDisplay(
763 int32_t displayId,
764 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
765 const auto it = touchStatesByDisplay.find(displayId);
766 if (it == touchStatesByDisplay.end()) {
767 return false;
768 }
769 const TouchState& state = it->second;
770 return state.hasActiveStylus();
771}
772
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800773Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
774 struct HashFunction {
775 size_t operator()(const WindowInfo& info) const { return info.id; }
776 };
777
778 std::unordered_set<WindowInfo, HashFunction> windowSet;
779 for (const WindowInfo& info : update.windowInfos) {
780 const auto [_, inserted] = windowSet.insert(info);
781 if (!inserted) {
782 return Error() << "Duplicate entry for " << info;
783 }
784 }
785 return {};
786}
787
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800788int32_t getUserActivityEventType(const EventEntry& eventEntry) {
789 switch (eventEntry.type) {
790 case EventEntry::Type::KEY: {
791 return USER_ACTIVITY_EVENT_BUTTON;
792 }
793 case EventEntry::Type::MOTION: {
794 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
795 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
796 return USER_ACTIVITY_EVENT_TOUCH;
797 }
798 return USER_ACTIVITY_EVENT_OTHER;
799 }
800 default: {
801 LOG_ALWAYS_FATAL("%s events are not user activity",
802 ftl::enum_string(eventEntry.type).c_str());
803 }
804 }
805}
806
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000807} // namespace
808
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809// --- InputDispatcher ---
810
Prabir Pradhana41d2442023-04-20 21:30:40 +0000811InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000812 : InputDispatcher(policy,
813 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
814 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000815
816InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
817 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700818 : mPolicy(policy),
819 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800821 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800822 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700823 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800824 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700825 mDispatchEnabled(false),
826 mDispatchFrozen(false),
827 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100828 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000829 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800830 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000831 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000832 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700833 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800834 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700836 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700837#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700838 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700839#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700840 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000841
842 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000843 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000844 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800845
846 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847}
848
849InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000850 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851
Prabir Pradhancef936d2021-07-21 16:17:52 +0000852 resetKeyRepeatLocked();
853 releasePendingEventLocked();
854 drainInboundQueueLocked();
855 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000857 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700858 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800859 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 }
861}
862
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700863status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700864 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700865 return ALREADY_EXISTS;
866 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700867 mThread = std::make_unique<InputThread>(
868 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
869 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700870}
871
872status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700873 if (mThread && mThread->isCallingThread()) {
874 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700875 return INVALID_OPERATION;
876 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700877 mThread.reset();
878 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700879}
880
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700882 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800884 std::scoped_lock _l(mLock);
885 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886
887 // Run a dispatch loop if there are no pending commands.
888 // The dispatch loop might enqueue commands to run afterwards.
889 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800890 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892
893 // Run all pending commands if there are any.
894 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000895 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700896 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800898
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 // If we are still waiting for ack on some events,
900 // we might have to wake up earlier to check if an app is anr'ing.
901 const nsecs_t nextAnrCheck = processAnrsLocked();
902 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
903
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800904 // We are about to enter an infinitely long sleep, because we have no commands or
905 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700906 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800907 mDispatcherEnteredIdle.notify_all();
908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 } // release lock
910
911 // Wait for callback or timeout or wake. (make sure we round up, not down)
912 nsecs_t currentTime = now();
913 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
914 mLooper->pollOnce(timeoutMillis);
915}
916
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700917/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500918 * Raise ANR if there is no focused window.
919 * Before the ANR is raised, do a final state check:
920 * 1. The currently focused application must be the same one we are waiting for.
921 * 2. Ensure we still don't have a focused window.
922 */
923void InputDispatcher::processNoFocusedWindowAnrLocked() {
924 // Check if the application that we are waiting for is still focused.
925 std::shared_ptr<InputApplicationHandle> focusedApplication =
926 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
927 if (focusedApplication == nullptr ||
928 focusedApplication->getApplicationToken() !=
929 mAwaitedFocusedApplication->getApplicationToken()) {
930 // Unexpected because we should have reset the ANR timer when focused application changed
931 ALOGE("Waited for a focused window, but focused application has already changed to %s",
932 focusedApplication->getName().c_str());
933 return; // The focused application has changed.
934 }
935
chaviw98318de2021-05-19 16:45:23 -0500936 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500937 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
938 if (focusedWindowHandle != nullptr) {
939 return; // We now have a focused window. No need for ANR.
940 }
941 onAnrLocked(mAwaitedFocusedApplication);
942}
943
944/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 * Check if any of the connections' wait queues have events that are too old.
946 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
947 * Return the time at which we should wake up next.
948 */
949nsecs_t InputDispatcher::processAnrsLocked() {
950 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700951 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700952 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
953 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
954 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500955 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700956 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500957 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700958 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500960 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700961 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
962 }
963 }
964
965 // Check if any connection ANRs are due
966 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
967 if (currentTime < nextAnrCheck) { // most likely scenario
968 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
969 }
970
971 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700972 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 if (connection == nullptr) {
974 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
975 return nextAnrCheck;
976 }
977 connection->responsive = false;
978 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800979 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000980 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700981 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700982}
983
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800984std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700985 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800986 if (connection->monitor) {
987 return mMonitorDispatchingTimeout;
988 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800989 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700990 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500991 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500993 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700994}
995
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800996void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 nsecs_t currentTime = now();
998
Jeff Browndc5992e2014-04-11 01:27:26 -0700999 // Reset the key repeat timer whenever normal dispatch is suspended while the
1000 // device is in a non-interactive state. This is to ensure that we abort a key
1001 // repeat if the device is just coming out of sleep.
1002 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 resetKeyRepeatLocked();
1004 }
1005
1006 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1007 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001008 if (DEBUG_FOCUS) {
1009 ALOGD("Dispatch frozen. Waiting some more.");
1010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 return;
1012 }
1013
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 // Ready to start a new event.
1015 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001017 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 // Synthesize a key repeat if appropriate.
1019 if (mKeyRepeatState.lastKeyEntry) {
1020 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1021 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1022 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001023 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
1025 }
1026
1027 // Nothing to do if there is no pending event.
1028 if (!mPendingEvent) {
1029 return;
1030 }
1031 } else {
1032 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001033 mPendingEvent = mInboundQueue.front();
1034 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 traceInboundQueueLengthLocked();
1036 }
1037
1038 // Poke user activity for this event.
1039 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001040 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
1043
1044 // Now we have an event to dispatch.
1045 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001046 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001048 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054
1055 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001056 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058
1059 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001060 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001061 const ConfigurationChangedEntry& typedEntry =
1062 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001064 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 break;
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 const DeviceResetEntry& typedEntry =
1070 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 break;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001076 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001077 std::shared_ptr<const FocusEntry> typedEntry =
1078 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001079 dispatchFocusLocked(currentTime, typedEntry);
1080 done = true;
1081 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1082 break;
1083 }
1084
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001085 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001086 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001087 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1088 done = true;
1089 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1090 break;
1091 }
1092
Prabir Pradhan99987712020-11-10 18:43:05 -08001093 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1094 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001095 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001096 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1097 done = true;
1098 break;
1099 }
1100
arthurhungb89ccb02020-12-30 16:19:01 +08001101 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001102 std::shared_ptr<const DragEntry> typedEntry =
1103 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001104 dispatchDragLocked(currentTime, typedEntry);
1105 done = true;
1106 break;
1107 }
1108
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001109 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001110 std::shared_ptr<const KeyEntry> keyEntry =
1111 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1116 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001118 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001119 if (done && mTracer) {
1120 ensureEventTraced(*keyEntry);
1121 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1122 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 break;
1124 }
1125
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001126 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001127 std::shared_ptr<const MotionEntry> motionEntry =
1128 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001129 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001130 // The event is stale. However, only drop stale events if there isn't an ongoing
1131 // gesture. That would allow us to complete the processing of the current stroke.
1132 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1133 if (touchStateIt != mTouchStatesByDisplay.end()) {
1134 const TouchState& touchState = touchStateIt->second;
1135 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1136 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1137 dropReason = DropReason::STALE;
1138 }
1139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001142 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1143 // Only drop events that are focus-dispatched.
1144 dropReason = DropReason::BLOCKED;
1145 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001147 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001148 if (done && mTracer) {
1149 ensureEventTraced(*motionEntry);
1150 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1151 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
Chris Yef59a2f42020-10-16 12:55:26 -07001154
1155 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001156 std::shared_ptr<const SensorEntry> sensorEntry =
1157 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001158
Chris Yef59a2f42020-10-16 12:55:26 -07001159 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1160 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1161 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1162 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1163 dropReason = DropReason::STALE;
1164 }
1165 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1166 done = true;
1167 break;
1168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170
1171 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001172 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
Michael Wright3a981722015-06-10 15:26:13 +01001175 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176
1177 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001178 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 }
1180}
1181
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001182bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001183 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001184}
1185
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001186/**
1187 * Return true if the events preceding this incoming motion event should be dropped
1188 * Return false otherwise (the default behaviour)
1189 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001190bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001191 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001192 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001193
1194 // Optimize case where the current application is unresponsive and the user
1195 // decides to touch a window in a different application.
1196 // If the application takes too long to catch up then we drop all events preceding
1197 // the touch into the other window.
1198 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001199 const int32_t displayId = motionEntry.displayId;
1200 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001201 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001202
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001203 sp<WindowInfoHandle> touchedWindowHandle =
1204 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001205 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 touchedWindowHandle->getApplicationToken() !=
1207 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001208 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001209 ALOGI("Pruning input queue because user touched a different application while waiting "
1210 "for %s",
1211 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001212 return true;
1213 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001214
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001215 // Alternatively, maybe there's a spy window that could handle this event.
1216 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1217 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1218 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001219 const std::shared_ptr<Connection> connection =
1220 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001221 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001222 // This spy window could take more input. Drop all events preceding this
1223 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001225 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 mAwaitedFocusedApplication->getName().c_str());
1227 return true;
1228 }
1229 }
1230 }
1231
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001232 return false;
1233}
1234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001238 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 traceInboundQueueLengthLocked();
1240
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001242 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001243 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1244 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001247 if (mTracer) {
1248 ensureEventTraced(keyEntry);
1249 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001250
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001251 // If a new up event comes in, and the pending event with same key code has been asked
1252 // to try again later because of the policy. We have to reset the intercept key wake up
1253 // time for it may have been handled in the policy and could be dropped.
1254 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1255 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001256 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001257 if (pendingKey.keyCode == keyEntry.keyCode &&
1258 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001259 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1260 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001261 pendingKey.interceptKeyWakeupTime = 0;
1262 needWake = true;
1263 }
1264 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 break;
1266 }
1267
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001268 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001269 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1270 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001271 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1272 if (mTracer) {
1273 ensureEventTraced(motionEntry);
1274 }
1275 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001276 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001277 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001279
1280 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1281 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1282 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1283 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1284 // and some other events have not yet been processed, the dispatcher will wait for
1285 // these events to be processed before dispatching the key event. This is because
1286 // the unprocessed events may cause the focus to change (for example, by launching a
1287 // new window or tapping a different window). To prevent waiting too long, we force
1288 // the key to be sent to the currently focused window when a new tap comes in.
1289 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1290 "just send the pending key event to the currently focused window.");
1291 mKeyIsWaitingForEventsTimeout = now();
1292 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001295 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001296 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1297 break;
1298 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001299 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001300 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001301 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001302 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001303 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1304 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001305 // nothing to do
1306 break;
1307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
1309
1310 return needWake;
1311}
1312
Prabir Pradhan24047542023-11-02 17:14:59 +00001313void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001314 // Do not store sensor event in recent queue to avoid flooding the queue.
1315 if (entry->type != EventEntry::Type::SENSOR) {
1316 mRecentQueue.push_back(entry);
1317 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001319 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321}
1322
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001323sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1324 bool isStylus,
1325 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001327 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001328 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001329 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001330 continue;
1331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001333 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001334 if (!info.isSpy() &&
1335 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001336 return windowHandle;
1337 }
1338 }
1339 return nullptr;
1340}
1341
1342std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001343 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001344 if (touchedWindow == nullptr) {
1345 return {};
1346 }
1347 // Traverse windows from front to back until we encounter the touched window.
1348 std::vector<InputTarget> outsideTargets;
1349 const auto& windowHandles = getWindowHandlesLocked(displayId);
1350 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1351 if (windowHandle == touchedWindow) {
1352 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1353 // below the touched window will not get ACTION_OUTSIDE event.
1354 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001355 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001356
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001357 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001358 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001359 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1360 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001361 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1362 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001363 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001366 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
Prabir Pradhand65552b2021-10-07 11:23:50 -07001369std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001370 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001371 // Traverse windows from front to back and gather the touched spy windows.
1372 std::vector<sp<WindowInfoHandle>> spyWindows;
1373 const auto& windowHandles = getWindowHandlesLocked(displayId);
1374 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1375 const WindowInfo& info = *windowHandle->getInfo();
1376
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001377 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001378 continue;
1379 }
1380 if (!info.isSpy()) {
1381 // The first touched non-spy window was found, so return the spy windows touched so far.
1382 return spyWindows;
1383 }
1384 spyWindows.push_back(windowHandle);
1385 }
1386 return spyWindows;
1387}
1388
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001389void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 const char* reason;
1391 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001392 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001393 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001394 ALOGD("Dropped event because policy consumed it.");
1395 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 reason = "inbound event was dropped because the policy consumed it";
1397 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001398 case DropReason::DISABLED:
1399 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 ALOGI("Dropped event because input dispatch is disabled.");
1401 }
1402 reason = "inbound event was dropped because input dispatch is disabled";
1403 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001404 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001405 LOG(INFO) << "Dropping because the current application is not responding and the user "
1406 "has started interacting with a different application: "
1407 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 reason = "inbound event was dropped because the current application is not responding "
1409 "and the user has started interacting with a different application";
1410 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001411 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001412 ALOGI("Dropped event because it is stale.");
1413 reason = "inbound event was dropped because it is stale";
1414 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 case DropReason::NO_POINTER_CAPTURE:
1416 ALOGI("Dropped event because there is no window with Pointer Capture.");
1417 reason = "inbound event was dropped because there is no window with Pointer Capture";
1418 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001419 case DropReason::NOT_DROPPED: {
1420 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 }
1424
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001426 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001427 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001428 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1429 options.displayId = keyEntry.displayId;
1430 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001434 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001435 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1436 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001437 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001438 options.displayId = motionEntry.displayId;
1439 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 synthesizeCancelationEventsForAllConnectionsLocked(options);
1441 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001442 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1443 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001444 options.displayId = motionEntry.displayId;
1445 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 synthesizeCancelationEventsForAllConnectionsLocked(options);
1447 }
1448 break;
1449 }
Chris Yef59a2f42020-10-16 12:55:26 -07001450 case EventEntry::Type::SENSOR: {
1451 break;
1452 }
arthurhungb89ccb02020-12-30 16:19:01 +08001453 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1454 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001455 break;
1456 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001457 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001458 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001459 case EventEntry::Type::CONFIGURATION_CHANGED:
1460 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001461 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001462 break;
1463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 }
1465}
1466
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469}
1470
Prabir Pradhancef936d2021-07-21 16:17:52 +00001471bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001472 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 return false;
1474 }
1475
1476 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001477 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001478 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001479 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1480 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001481 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 return true;
1483}
1484
Prabir Pradhancef936d2021-07-21 16:17:52 +00001485void InputDispatcher::postCommandLocked(Command&& command) {
1486 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487}
1488
1489void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001490 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001491 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 releaseInboundEventLocked(entry);
1494 }
1495 traceInboundQueueLengthLocked();
1496}
1497
1498void InputDispatcher::releasePendingEventLocked() {
1499 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001501 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503}
1504
Prabir Pradhan24047542023-11-02 17:14:59 +00001505void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001506 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001508 if (DEBUG_DISPATCH_CYCLE) {
1509 ALOGD("Injected inbound event was dropped.");
1510 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001514 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 }
1516 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517}
1518
1519void InputDispatcher::resetKeyRepeatLocked() {
1520 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001521 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 }
1523}
1524
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001525std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001526 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
Michael Wright2e732952014-09-24 13:26:59 -07001528 uint32_t policyFlags = entry->policyFlags &
1529 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001532 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1533 currentTime, entry->deviceId, entry->source,
1534 entry->displayId, policyFlags, entry->action, entry->flags,
1535 entry->keyCode, entry->scanCode, entry->metaState,
1536 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001538 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001539 if (mTracer) {
1540 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1541 }
1542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001543 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001545 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546}
1547
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1551 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553
1554 // Reset key repeating in case a keyboard device was added or removed or something.
1555 resetKeyRepeatLocked();
1556
1557 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001558 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1559 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001560 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001561 };
1562 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return true;
1564}
1565
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001566bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1567 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001568 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1569 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1570 entry.deviceId);
1571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572
liushenxiang42232912021-05-21 20:24:09 +08001573 // Reset key repeating in case a keyboard device was disabled or enabled.
1574 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1575 resetKeyRepeatLocked();
1576 }
1577
Michael Wrightfb04fd52022-11-24 22:31:11 +00001578 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001581
1582 // Remove all active pointers from this device
1583 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1584 touchState.removeAllPointersForDevice(entry.deviceId);
1585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return true;
1587}
1588
Vishnu Nairad321cd2020-08-20 16:40:21 -07001589void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001590 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001591 if (mPendingEvent != nullptr) {
1592 // Move the pending event to the front of the queue. This will give the chance
1593 // for the pending event to get dispatched to the newly focused window
1594 mInboundQueue.push_front(mPendingEvent);
1595 mPendingEvent = nullptr;
1596 }
1597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001598 std::unique_ptr<FocusEntry> focusEntry =
1599 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1600 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001601
1602 // This event should go to the front of the queue, but behind all other focus events
1603 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001604 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1605 [](const std::shared_ptr<const EventEntry>& event) {
1606 return event->type == EventEntry::Type::FOCUS;
1607 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001608
1609 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001610 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001611}
1612
Prabir Pradhan24047542023-11-02 17:14:59 +00001613void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1614 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001615 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1616 if (connection == nullptr) {
1617 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001618 }
1619 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001620 target.connection = connection;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001621 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001622 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001623 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001624 std::string reason = std::string("reason=").append(entry->reason);
1625 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001626 dispatchEventLocked(currentTime, entry, {target});
1627}
1628
Prabir Pradhan99987712020-11-10 18:43:05 -08001629void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001630 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001631 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001632 dropReason = DropReason::NOT_DROPPED;
1633
Prabir Pradhan99987712020-11-10 18:43:05 -08001634 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001635 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001636
1637 if (entry->pointerCaptureRequest.enable) {
1638 // Enable Pointer Capture.
1639 if (haveWindowWithPointerCapture &&
1640 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001641 // This can happen if pointer capture is disabled and re-enabled before we notify the
1642 // app of the state change, so there is no need to notify the app.
1643 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1644 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001645 }
1646 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001647 // This can happen if a window requests capture and immediately releases capture.
1648 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001649 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001650 return;
1651 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001652 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1653 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1654 return;
1655 }
1656
Vishnu Nairc519ff72021-01-21 08:23:08 -08001657 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001658 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1659 mWindowTokenWithPointerCapture = token;
1660 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 // Disable Pointer Capture.
1662 // We do not check if the sequence number matches for requests to disable Pointer Capture
1663 // for two reasons:
1664 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1665 // to disable capture with the same sequence number: one generated by
1666 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1667 // Capture being disabled in InputReader.
1668 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1669 // actual Pointer Capture state that affects events being generated by input devices is
1670 // in InputReader.
1671 if (!haveWindowWithPointerCapture) {
1672 // Pointer capture was already forcefully disabled because of focus change.
1673 dropReason = DropReason::NOT_DROPPED;
1674 return;
1675 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001676 token = mWindowTokenWithPointerCapture;
1677 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001678 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001679 setPointerCaptureLocked(false);
1680 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001681 }
1682
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001683 auto connection = getConnectionLocked(token);
1684 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001685 // Window has gone away, clean up Pointer Capture state.
1686 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001687 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001688 setPointerCaptureLocked(false);
1689 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001690 return;
1691 }
1692 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001693 target.connection = connection;
Prabir Pradhan99987712020-11-10 18:43:05 -08001694 entry->dispatchInProgress = true;
1695 dispatchEventLocked(currentTime, entry, {target});
1696
1697 dropReason = DropReason::NOT_DROPPED;
1698}
1699
Prabir Pradhan24047542023-11-02 17:14:59 +00001700void InputDispatcher::dispatchTouchModeChangeLocked(
1701 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001702 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001703 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 if (windowHandles.empty()) {
1705 return;
1706 }
1707 const std::vector<InputTarget> inputTargets =
1708 getInputTargetsFromWindowHandlesLocked(windowHandles);
1709 if (inputTargets.empty()) {
1710 return;
1711 }
1712 entry->dispatchInProgress = true;
1713 dispatchEventLocked(currentTime, entry, inputTargets);
1714}
1715
1716std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1717 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1718 std::vector<InputTarget> inputTargets;
1719 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001720 const sp<IBinder>& token = handle->getToken();
1721 if (token == nullptr) {
1722 continue;
1723 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001724 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1725 if (connection == nullptr) {
1726 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001727 }
1728 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001729 target.connection = connection;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001730 inputTargets.push_back(target);
1731 }
1732 return inputTargets;
1733}
1734
Prabir Pradhan24047542023-11-02 17:14:59 +00001735bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001736 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 if (!entry->dispatchInProgress) {
1739 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1740 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1741 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1742 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001743 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 // We have seen two identical key downs in a row which indicates that the device
1745 // driver is automatically generating key repeats itself. We take note of the
1746 // repeat here, but we disable our own next key repeat timer since it is clear that
1747 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001748 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1749 // Make sure we don't get key down from a different device. If a different
1750 // device Id has same key pressed down, the new device Id will replace the
1751 // current one to hold the key repeat with repeat count reset.
1752 // In the future when got a KEY_UP on the device id, drop it and do not
1753 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1755 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001756 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 } else {
1758 // Not a repeat. Save key down state in case we do see a repeat later.
1759 resetKeyRepeatLocked();
1760 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1761 }
1762 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001763 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1764 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001765 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001766 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001767 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1768 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001769 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 resetKeyRepeatLocked();
1771 }
1772
1773 if (entry->repeatCount == 1) {
1774 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1775 } else {
1776 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1777 }
1778
1779 entry->dispatchInProgress = true;
1780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001781 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 }
1783
1784 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001785 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001787 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 return false; // wait until next wakeup
1789 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001790 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 entry->interceptKeyWakeupTime = 0;
1792 }
1793
1794 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001795 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001797 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001798 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001799
1800 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1801 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1802 };
1803 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001804 // Poke user activity for keys not passed to user
1805 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 return false; // wait for the command to run
1807 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001808 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001810 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001811 if (*dropReason == DropReason::NOT_DROPPED) {
1812 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 }
1814 }
1815
1816 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001817 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001818 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001819 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1820 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001821 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001822 // Poke user activity for undispatched keys
1823 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 return true;
1825 }
1826
1827 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001828 InputEventInjectionResult injectionResult;
1829 sp<WindowInfoHandle> focusedWindow =
1830 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1831 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 return false;
1834 }
1835
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001836 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 return true;
1839 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001840 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1841
1842 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001843 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1844 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001846 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001847 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001849 if (mTracer) {
1850 ensureEventTraced(*entry);
1851 for (const auto& target : inputTargets) {
1852 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1853 }
1854 }
1855
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 // Dispatch the key.
1857 dispatchEventLocked(currentTime, entry, inputTargets);
1858 return true;
1859}
1860
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001862 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1863 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1864 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1865 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1866 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1867 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1868 entry.metaState, entry.repeatCount, entry.downTime);
1869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870}
1871
Prabir Pradhancef936d2021-07-21 16:17:52 +00001872void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001873 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001874 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001875 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1876 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1877 "source=0x%x, sensorType=%s",
1878 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001879 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001880 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001881 auto command = [this, entry]() REQUIRES(mLock) {
1882 scoped_unlock unlock(mLock);
1883
1884 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001885 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001886 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001887 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1888 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001889 };
1890 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001891}
1892
1893bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001894 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1895 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001896 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001897 }
Chris Yef59a2f42020-10-16 12:55:26 -07001898 { // acquire lock
1899 std::scoped_lock _l(mLock);
1900
1901 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001902 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001903 if (entry->type == EventEntry::Type::SENSOR) {
1904 it = mInboundQueue.erase(it);
1905 releaseInboundEventLocked(entry);
1906 }
1907 }
1908 }
1909 return true;
1910}
1911
Prabir Pradhan24047542023-11-02 17:14:59 +00001912bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1913 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001914 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001917 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 entry->dispatchInProgress = true;
1919
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001920 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 }
1922
1923 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001924 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001925 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1927 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 return true;
1929 }
1930
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001931 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001934 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 if (isPointerEvent) {
1938 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001939
1940 if (mDragState &&
1941 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1942 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1943 pilferPointersLocked(mDragState->dragWindow->getToken());
1944 }
1945
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001946 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001947 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001948 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1949 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 } else {
1951 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001952 sp<WindowInfoHandle> focusedWindow =
1953 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1954 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1955 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001956 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1957 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1958 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001961 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 return false;
1963 }
1964
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001965 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001966 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001967 return true;
1968 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001970 CancelationOptions::Mode mode(
1971 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1972 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001973 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001974 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001975 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 return true;
1977 }
1978
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001979 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001980 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001982 if (mTracer) {
1983 ensureEventTraced(*entry);
1984 for (const auto& target : inputTargets) {
1985 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1986 }
1987 }
1988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 dispatchEventLocked(currentTime, entry, inputTargets);
1991 return true;
1992}
1993
chaviw98318de2021-05-19 16:45:23 -05001994void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001995 bool isExiting, const int32_t rawX,
1996 const int32_t rawY) {
1997 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001998 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001999 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2000 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002001
2002 enqueueInboundEventLocked(std::move(dragEntry));
2003}
2004
Prabir Pradhan24047542023-11-02 17:14:59 +00002005void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2006 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002007 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2008 if (connection == nullptr) {
2009 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002010 }
2011 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002012 target.connection = connection;
arthurhungb89ccb02020-12-30 16:19:01 +08002013 entry->dispatchInProgress = true;
2014 dispatchEventLocked(currentTime, entry, {target});
2015}
2016
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002017void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002018 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002019 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002020 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002021 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002022 "metaState=0x%x, buttonState=0x%x,"
2023 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002024 prefix, entry.eventTime, entry.deviceId,
2025 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2026 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2027 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2028 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002030 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002031 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002032 "x=%f, y=%f, pressure=%f, size=%f, "
2033 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2034 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002035 i, entry.pointerProperties[i].id,
2036 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002037 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2038 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2039 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2040 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2041 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2042 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2043 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2044 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2045 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048}
2049
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002050void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002051 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002054 if (DEBUG_DISPATCH_CYCLE) {
2055 ALOGD("dispatchEventToCurrentInputTargets");
2056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002058 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2061
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002062 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002064 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002065 std::shared_ptr<Connection> connection = inputTarget.connection;
2066 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
2068}
2069
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002070void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2072 // If the policy decides to close the app, we will get a channel removal event via
2073 // unregisterInputChannel, and will clean up the connection that way. We are already not
2074 // sending new pointers to the connection when it blocked, but focused events will continue to
2075 // pile up.
2076 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002077 connection->getInputChannelName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002078 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002079 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002080 "application not responding");
2081 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
2083}
2084
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002086 if (DEBUG_FOCUS) {
2087 ALOGD("Resetting ANR timeouts.");
2088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089
2090 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002092 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093}
2094
Tiger Huang721e26f2018-07-24 22:26:19 +08002095/**
2096 * Get the display id that the given event should go to. If this event specifies a valid display id,
2097 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2098 * Focused display is the display that the user most recently interacted with.
2099 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002101 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002103 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002104 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2105 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002106 break;
2107 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002108 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002109 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2110 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002111 break;
2112 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002113 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002114 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002115 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002116 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002117 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002118 case EventEntry::Type::SENSOR:
2119 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002120 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 return ADISPLAY_ID_NONE;
2122 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002123 }
2124 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2125}
2126
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002127bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2128 const char* focusedWindowName) {
2129 if (mAnrTracker.empty()) {
2130 // already processed all events that we waited for
2131 mKeyIsWaitingForEventsTimeout = std::nullopt;
2132 return false;
2133 }
2134
2135 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2136 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002137 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002138 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002139 std::chrono::duration_cast<std::chrono::nanoseconds>(
2140 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002141 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002142 return true;
2143 }
2144
2145 // We still have pending events, and already started the timer
2146 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2147 return true; // Still waiting
2148 }
2149
2150 // Waited too long, and some connection still hasn't processed all motions
2151 // Just send the key to the focused window
2152 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2153 focusedWindowName);
2154 mKeyIsWaitingForEventsTimeout = std::nullopt;
2155 return false;
2156}
2157
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002158sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002159 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002161 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162
Tiger Huang721e26f2018-07-24 22:26:19 +08002163 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002164 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002165 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002166 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2167
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 // If there is no currently focused window and no focused application
2169 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2171 ALOGI("Dropping %s event because there is no focused window or focused application in "
2172 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002173 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002174 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 }
2176
Vishnu Nair062a8672021-09-03 16:07:44 -07002177 // Drop key events if requested by input feature
2178 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002180 }
2181
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2183 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2184 // start interacting with another application via touch (app switch). This code can be removed
2185 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2186 // an app is expected to have a focused window.
2187 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2188 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2189 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002190 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2191 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2192 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002193 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002194 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002195 ALOGW("Waiting because no window has focus but %s may eventually add a "
2196 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002197 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002198 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002199 outInjectionResult = InputEventInjectionResult::PENDING;
2200 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2202 // Already raised ANR. Drop the event
2203 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002204 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002205 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 } else {
2207 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002208 outInjectionResult = InputEventInjectionResult::PENDING;
2209 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 }
2211 }
2212
2213 // we have a valid, non-null focused window
2214 resetNoFocusedWindowTimeoutLocked();
2215
Prabir Pradhan5735a322022-04-11 17:23:34 +00002216 // Verify targeted injection.
2217 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2218 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002219 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2220 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002223 if (focusedWindowHandle->getInfo()->inputConfig.test(
2224 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002225 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002226 outInjectionResult = InputEventInjectionResult::PENDING;
2227 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002228 }
2229
2230 // If the event is a key event, then we must wait for all previous events to
2231 // complete before delivering it because previous events may have the
2232 // side-effect of transferring focus to a different window and we want to
2233 // ensure that the following keys are sent to the new window.
2234 //
2235 // Suppose the user touches a button in a window then immediately presses "A".
2236 // If the button causes a pop-up window to appear then we want to ensure that
2237 // the "A" key is delivered to the new pop-up window. This is because users
2238 // often anticipate pending UI changes when typing on a keyboard.
2239 // To obtain this behavior, we must serialize key events with respect to all
2240 // prior input events.
2241 if (entry.type == EventEntry::Type::KEY) {
2242 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002243 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002244 outInjectionResult = InputEventInjectionResult::PENDING;
2245 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 }
2248
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002249 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2250 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251}
2252
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002253/**
2254 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2255 * that are currently unresponsive.
2256 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002257std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2258 const std::vector<Monitor>& monitors) const {
2259 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002261 [](const Monitor& monitor) REQUIRES(mLock) {
2262 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002263 if (!connection->responsive) {
2264 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002265 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002266 return false;
2267 }
2268 return true;
2269 });
2270 return responsiveMonitors;
2271}
2272
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002273std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002274 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002275 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002276 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002278 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // For security reasons, we defer updating the touch state until we are sure that
2280 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281 const int32_t displayId = entry.displayId;
2282 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002283 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002286 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 // Copy current touch state into tempTouchState.
2289 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2290 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002291 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002292 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2294 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002295 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002296 }
2297
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002298 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002299
2300 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2301 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2302 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002303 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2304 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002305 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002306 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2307 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002308 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2309 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2310 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002311 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002312
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002313 if (newGesture) {
2314 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002315 }
2316
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002317 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2318 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2319 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002322 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002323 if (wasDown) {
2324 // Started hovering, but the device is already down: reject the hover event
2325 LOG(ERROR) << "Got hover event " << entry.getDescription()
2326 << " but the device is already down " << oldState->dump();
2327 outInjectionResult = InputEventInjectionResult::FAILED;
2328 return {};
2329 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002330 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2331 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002332 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2336 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002337 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002338 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002339 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002340 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2341 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002342 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002343 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002344 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002345
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002346 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002347 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002350 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002351 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002354 }
2355
Prabir Pradhan5735a322022-04-11 17:23:34 +00002356 // Verify targeted injection.
2357 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2358 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002359 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002360 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002361 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002362 }
2363
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002364 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002365 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2367 // New window supports splitting, but we should never split mouse events.
2368 isSplit = !isFromMouse;
2369 } else if (isSplit) {
2370 // New window does not support splitting but we have already split events.
2371 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002372 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2373 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002374 newTouchedWindowHandle = nullptr;
2375 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002376 } else {
2377 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002378 // be delivered to a new window which supports split touch. Pointers from a mouse device
2379 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002380 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002381 }
2382
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002383 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002384 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002386 // Process the foreground window first so that it is the first to receive the event.
2387 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 }
2389
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002390 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002391 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2392 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002393 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002394 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002395 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002396 }
2397
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002398 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002399 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 continue;
2401 }
2402
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002403 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002405 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002406 }
2407
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002408 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002409 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002411 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2412 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002414 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415
2416 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002417 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418 }
2419 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002424
2425 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002426
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002427 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002428 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2429 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002430 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002431 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002432 isDownOrPointerDown
2433 ? std::make_optional(entry.eventTime)
2434 : std::nullopt);
2435 // If this is the pointer going down and the touched window has a wallpaper
2436 // then also add the touched wallpaper windows so they are locked in for the
2437 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2438 // SCROLL because the wallpaper engine only supports touch events. We would need to
2439 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2440 // handle these events.
2441 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002442 windowHandle->getInfo()->inputConfig.test(
2443 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2444 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2445 if (wallpaper != nullptr) {
2446 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2447 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002448 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002449 if (isSplit) {
2450 wallpaperFlags |= InputTarget::Flags::SPLIT;
2451 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002452 tempTouchState.addOrUpdateWindow(wallpaper,
2453 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002454 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002455 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002456 }
2457 }
2458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002460
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002461 // If a window is already pilfering some pointers, give it this new pointer as well and
2462 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2463 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002464 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002465 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002466 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002467 // This window is already pilfering some pointers, and this new pointer is also
2468 // going to it. Therefore, take over this pointer and don't give it to anyone
2469 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002470 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002471 }
2472 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002473
2474 // Restrict all pilfered pointers to the pilfering windows.
2475 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 } else {
2477 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2478
2479 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002480 if (!tempTouchState.isDown(entry.deviceId) &&
2481 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002482 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2483 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2484 << " is not down or we previously dropped the pointer down event in "
2485 << "display " << displayId << ": " << entry.getDescription();
2486 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002487 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002488 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002491 // If the pointer is not currently hovering, then ignore the event.
2492 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2493 const int32_t pointerId = entry.pointerProperties[0].id;
2494 if (oldState == nullptr ||
2495 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2496 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2497 "display "
2498 << displayId << ": " << entry.getDescription();
2499 outInjectionResult = InputEventInjectionResult::FAILED;
2500 return {};
2501 }
2502 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2503 }
2504
arthurhung6d4bed92021-03-17 11:59:33 +08002505 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002506
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002508 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002509 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002510 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002511 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002512 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002513 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002514 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002515 sp<WindowInfoHandle> newTouchedWindowHandle =
2516 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002517
Prabir Pradhan5735a322022-04-11 17:23:34 +00002518 // Verify targeted injection.
2519 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2520 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002521 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002522 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002523 }
2524
Vishnu Nair062a8672021-09-03 16:07:44 -07002525 // Drop touch events if requested by input feature
2526 if (newTouchedWindowHandle != nullptr &&
2527 shouldDropInput(entry, newTouchedWindowHandle)) {
2528 newTouchedWindowHandle = nullptr;
2529 }
2530
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002531 if (newTouchedWindowHandle != nullptr &&
2532 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002533 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002534 oldTouchedWindowHandle->getName().c_str(),
2535 newTouchedWindowHandle->getName().c_str(), displayId);
2536
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002538 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002539 const PointerProperties& pointer = entry.pointerProperties[0];
2540 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002541
2542 const TouchedWindow& touchedWindow =
2543 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002544 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002545 InputTarget::DispatchMode::SLIPPERY_EXIT,
2546 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002547 touchedWindow.getDownTimeInTarget(entry.deviceId),
2548 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549
2550 // Make a slippery entrance into the new window.
2551 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002552 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 }
2554
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002555 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002556 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002557 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002564 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002565 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 }
2567
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002568 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2569 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002570 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002571 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002572
2573 // Check if the wallpaper window should deliver the corresponding event.
2574 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002575 tempTouchState, entry.deviceId, pointer, targets);
2576 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002577 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
2579 }
Arthur Hung96483742022-11-15 03:30:48 +00002580
2581 // Update the pointerIds for non-splittable when it received pointer down.
2582 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2583 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002584 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002585 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2586 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002587 // Ignore drag window for it should just track one pointer.
2588 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2589 continue;
2590 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002591 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002592 }
2593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 }
2595
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002596 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002597 {
2598 std::vector<TouchedWindow> hoveringWindows =
2599 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2600 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002601 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002602 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2603 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002604 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002605 if (!target) {
2606 continue;
2607 }
2608 // Hardcode to single hovering pointer for now.
2609 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2610 pointerIds.set(entry.pointerProperties[0].id);
2611 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2612 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615
Prabir Pradhan5735a322022-04-11 17:23:34 +00002616 // Ensure that all touched windows are valid for injection.
2617 if (entry.injectionState != nullptr) {
2618 std::string errs;
2619 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002620 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2621 if (err) errs += "\n - " + *err;
2622 }
2623 if (!errs.empty()) {
2624 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002625 "%s:%s",
2626 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002627 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002628 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002629 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002630 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002631
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002632 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2633 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002635 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002636 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002637 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002638 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002640 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002642 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002643 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2644 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
2647 }
2648 }
2649 }
2650
Harry Cuttsb166c002023-05-09 13:06:05 +00002651 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2652 // only want the system UI to handle these gestures.
2653 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2654 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2655 if (isTouchpadNavGesture) {
2656 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2657 }
2658
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002659 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002660 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002661 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002662 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002663 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002664 continue;
2665 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002666 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002667 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002668 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002669 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002670
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002671 // During targeted injection, only allow owned targets to receive events
2672 std::erase_if(targets, [&](const InputTarget& target) {
2673 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2674 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2675 if (err) {
2676 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2677 << ": " << (*err);
2678 return true;
2679 }
2680 return false;
2681 });
2682
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002683 if (targets.empty()) {
2684 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2685 outInjectionResult = InputEventInjectionResult::FAILED;
2686 return {};
2687 }
2688
2689 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2690 // window that is actually receiving the entire gesture.
2691 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002692 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002693 })) {
2694 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2695 << entry.getDescription();
2696 outInjectionResult = InputEventInjectionResult::FAILED;
2697 return {};
2698 }
2699
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002700 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701
Prabir Pradhan502a7252023-12-01 16:11:24 +00002702 // Now that we have generated all of the input targets for this event, reset the dispatch
2703 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002704 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002705 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002706 }
2707
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002708 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002709 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002710 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002711 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002712 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002713 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002714 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2716 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002717 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2718 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2719 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
2721
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 // Save changes unless the action was scroll in which case the temporary touch
2723 // state was only valid for this one action.
2724 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002725 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002726 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002727 mTouchStatesByDisplay[displayId] = tempTouchState;
2728 } else {
2729 mTouchStatesByDisplay.erase(displayId);
2730 }
2731 }
2732
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002733 if (tempTouchState.windows.empty()) {
2734 mTouchStatesByDisplay.erase(displayId);
2735 }
2736
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002737 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738}
2739
arthurhung6d4bed92021-03-17 11:59:33 +08002740void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002741 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2742 // have an explicit reason to support it.
2743 constexpr bool isStylus = false;
2744
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002745 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002746 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002747 if (dropWindow) {
2748 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002749 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002750 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002751 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002752 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002753 }
2754 mDragState.reset();
2755}
2756
2757void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002758 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002759 return;
2760 }
2761
arthurhung6d4bed92021-03-17 11:59:33 +08002762 if (!mDragState->isStartDrag) {
2763 mDragState->isStartDrag = true;
2764 mDragState->isStylusButtonDownAtStart =
2765 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2766 }
2767
Arthur Hung54745652022-04-20 07:17:41 +00002768 // Find the pointer index by id.
2769 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002770 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002771 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2772 if (pointerProperties.id == mDragState->pointerId) {
2773 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002774 }
Arthur Hung54745652022-04-20 07:17:41 +00002775 }
arthurhung6d4bed92021-03-17 11:59:33 +08002776
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002777 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002778 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002779 }
2780
2781 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2782 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2783 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2784
2785 switch (maskedAction) {
2786 case AMOTION_EVENT_ACTION_MOVE: {
2787 // Handle the special case : stylus button no longer pressed.
2788 bool isStylusButtonDown =
2789 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2790 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2791 finishDragAndDrop(entry.displayId, x, y);
2792 return;
2793 }
2794
2795 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2796 // until we have an explicit reason to support it.
2797 constexpr bool isStylus = false;
2798
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002799 sp<WindowInfoHandle> hoverWindowHandle =
2800 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2801 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002802 // enqueue drag exit if needed.
2803 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2804 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2805 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002806 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002807 y);
2808 }
2809 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2810 }
2811 // enqueue drag location if needed.
2812 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002813 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002814 }
2815 break;
2816 }
2817
2818 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002819 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002820 break;
2821 }
2822 // The drag pointer is up.
2823 [[fallthrough]];
2824 case AMOTION_EVENT_ACTION_UP:
2825 finishDragAndDrop(entry.displayId, x, y);
2826 break;
2827 case AMOTION_EVENT_ACTION_CANCEL: {
2828 ALOGD("Receiving cancel when drag and drop.");
2829 sendDropWindowCommandLocked(nullptr, 0, 0);
2830 mDragState.reset();
2831 break;
2832 }
arthurhungb89ccb02020-12-30 16:19:01 +08002833 }
2834}
2835
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002836std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2837 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002838 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002839 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002840 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2841 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002842 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2843 return {};
2844 }
2845 InputTarget inputTarget;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002846 inputTarget.connection = connection;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002847 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002848 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002849 inputTarget.flags = targetFlags;
2850 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2851 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2852 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2853 if (displayInfoIt != mDisplayInfos.end()) {
2854 inputTarget.displayTransform = displayInfoIt->second.transform;
2855 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002856 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002857 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2858 }
2859 return inputTarget;
2860}
2861
chaviw98318de2021-05-19 16:45:23 -05002862void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002863 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002864 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002865 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002866 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002867 std::vector<InputTarget>::iterator it =
2868 std::find_if(inputTargets.begin(), inputTargets.end(),
2869 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002870 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002871 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002872
chaviw98318de2021-05-19 16:45:23 -05002873 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002874
2875 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002876 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002877 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2878 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002879 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002880 return;
2881 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002882 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883 it = inputTargets.end() - 1;
2884 }
2885
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002886 if (it->flags != targetFlags) {
2887 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2888 }
2889 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2890 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2891 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2892 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002893}
2894
2895void InputDispatcher::addPointerWindowTargetLocked(
2896 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002897 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2898 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2899 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002900 if (pointerIds.none()) {
2901 for (const auto& target : inputTargets) {
2902 LOG(INFO) << "Target: " << target;
2903 }
2904 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2905 return;
2906 }
2907 std::vector<InputTarget>::iterator it =
2908 std::find_if(inputTargets.begin(), inputTargets.end(),
2909 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002910 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002911 });
2912
2913 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2914 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2915 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2916 // input targets for hovering pointers and for touching pointers.
2917 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2918 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002919 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002920 // Force the code below to create a new input target
2921 it = inputTargets.end();
2922 }
2923
2924 const WindowInfo* windowInfo = windowHandle->getInfo();
2925
2926 if (it == inputTargets.end()) {
2927 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002928 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2929 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002930 if (!target) {
2931 return;
2932 }
2933 inputTargets.push_back(*target);
2934 it = inputTargets.end() - 1;
2935 }
2936
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002937 if (it->dispatchMode != dispatchMode) {
2938 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2939 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2940 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002941 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002942 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2943 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002944 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002945 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002946 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002947 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2948 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002949
chaviw1ff3d1e2020-07-01 15:53:47 -07002950 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951}
2952
Michael Wright3dd60e22019-03-27 22:06:44 +00002953void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002954 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002955 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2956 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002957
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002958 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2959 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002960 target.connection = monitor.connection;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002961 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2962 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002963 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2964 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002965 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002966 target.setDefaultPointerTransform(target.displayTransform);
2967 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 }
2969}
2970
Robert Carrc9bf1d32020-04-13 17:21:08 -07002971/**
2972 * Indicate whether one window handle should be considered as obscuring
2973 * another window handle. We only check a few preconditions. Actually
2974 * checking the bounds is left to the caller.
2975 */
chaviw98318de2021-05-19 16:45:23 -05002976static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2977 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002978 // Compare by token so cloned layers aren't counted
2979 if (haveSameToken(windowHandle, otherHandle)) {
2980 return false;
2981 }
2982 auto info = windowHandle->getInfo();
2983 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002984 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002985 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002986 } else if (otherInfo->alpha == 0 &&
2987 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002988 // Those act as if they were invisible, so we don't need to flag them.
2989 // We do want to potentially flag touchable windows even if they have 0
2990 // opacity, since they can consume touches and alter the effects of the
2991 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002992 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002993 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2994 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002995 } else if (info->ownerUid == otherInfo->ownerUid) {
2996 // If ownerUid is the same we don't generate occlusion events as there
2997 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002998 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002999 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003000 return false;
3001 } else if (otherInfo->displayId != info->displayId) {
3002 return false;
3003 }
3004 return true;
3005}
3006
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003007/**
3008 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3009 * untrusted, one should check:
3010 *
3011 * 1. If result.hasBlockingOcclusion is true.
3012 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3013 * BLOCK_UNTRUSTED.
3014 *
3015 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3016 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3017 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3018 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3019 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3020 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3021 *
3022 * If neither of those is true, then it means the touch can be allowed.
3023 */
3024InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003025 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3026 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003027 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003028 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003029 TouchOcclusionInfo info;
3030 info.hasBlockingOcclusion = false;
3031 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003032 info.obscuringUid = gui::Uid::INVALID;
3033 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003034 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003035 if (windowHandle == otherHandle) {
3036 break; // All future windows are below us. Exit early.
3037 }
chaviw98318de2021-05-19 16:45:23 -05003038 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003039 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3040 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003041 if (DEBUG_TOUCH_OCCLUSION) {
3042 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003043 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003044 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003045 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3046 // we perform the checks below to see if the touch can be propagated or not based on the
3047 // window's touch occlusion mode
3048 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3049 info.hasBlockingOcclusion = true;
3050 info.obscuringUid = otherInfo->ownerUid;
3051 info.obscuringPackage = otherInfo->packageName;
3052 break;
3053 }
3054 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003055 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003056 float opacity =
3057 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3058 // Given windows A and B:
3059 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3060 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3061 opacityByUid[uid] = opacity;
3062 if (opacity > info.obscuringOpacity) {
3063 info.obscuringOpacity = opacity;
3064 info.obscuringUid = uid;
3065 info.obscuringPackage = otherInfo->packageName;
3066 }
3067 }
3068 }
3069 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003070 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003071 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003072 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003073 return info;
3074}
3075
chaviw98318de2021-05-19 16:45:23 -05003076std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003077 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003078 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003079 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3080 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3081 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003082 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003083 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003084 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3085 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003086 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3087 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3088 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003089 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003090}
3091
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003092bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3093 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003094 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3095 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003096 return false;
3097 }
3098 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003099 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003100 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003101 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003102 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3103 return false;
3104 }
3105 return true;
3106}
3107
chaviw98318de2021-05-19 16:45:23 -05003108bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003111 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3112 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003113 if (windowHandle == otherHandle) {
3114 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
chaviw98318de2021-05-19 16:45:23 -05003116 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003117 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003118 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 return true;
3120 }
3121 }
3122 return false;
3123}
3124
chaviw98318de2021-05-19 16:45:23 -05003125bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003126 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003127 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3128 const WindowInfo* windowInfo = windowHandle->getInfo();
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 Wrightcdcd8f22016-03-22 16:52:13 -07003132 }
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->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003136 return true;
3137 }
3138 }
3139 return false;
3140}
3141
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003142std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003143 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003144 if (applicationHandle != nullptr) {
3145 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003146 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 } else {
3148 return applicationHandle->getName();
3149 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003150 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003151 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003153 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
3155}
3156
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003157void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003158 if (!isUserActivityEvent(eventEntry)) {
3159 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003160 return;
3161 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003162
3163 const int32_t eventType = getUserActivityEventType(eventEntry);
3164 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3165 // Note that we're directly getting the time diff between the current event and the previous
3166 // event. This is assuming that the first user event always happens at a timestamp that is
3167 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3168 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3169 // value than the potential first user activity event time, so this is ok.
3170 std::chrono::nanoseconds timeSinceLastEvent =
3171 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3172 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3173 return;
3174 }
3175 }
3176
Tiger Huang721e26f2018-07-24 22:26:19 +08003177 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003178 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003179 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003180 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003181 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003182 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003183 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 }
3185 }
3186
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003187 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003188 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003189 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3190 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 return;
3192 }
Josep del Riob3981622023-04-18 15:49:45 +00003193 if (windowDisablingUserActivityInfo != nullptr) {
3194 if (DEBUG_DISPATCH_CYCLE) {
3195 ALOGD("Not poking user activity: disabled by window '%s'.",
3196 windowDisablingUserActivityInfo->name.c_str());
3197 }
3198 return;
3199 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003202 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003203 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3204 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 return;
3206 }
Josep del Riob3981622023-04-18 15:49:45 +00003207 // If the key code is unknown, we don't consider it user activity
3208 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3209 return;
3210 }
3211 // Don't inhibit events that were intercepted or are not passed to
3212 // the apps, like system shortcuts
3213 if (windowDisablingUserActivityInfo != nullptr &&
3214 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3215 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3216 if (DEBUG_DISPATCH_CYCLE) {
3217 ALOGD("Not poking user activity: disabled by window '%s'.",
3218 windowDisablingUserActivityInfo->name.c_str());
3219 }
3220 return;
3221 }
3222
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003225 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003226 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003227 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003228 break;
3229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
3231
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003232 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003233 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3234 REQUIRES(mLock) {
3235 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003236 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003237 };
3238 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003242 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003243 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003244 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003245 ATRACE_NAME_IF(ATRACE_ENABLED(),
3246 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3247 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003248 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003249 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003250 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003251 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003252 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003253 inputTarget.getPointerInfoString().c_str());
3254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255
3256 // Skip this event if the connection status is not normal.
3257 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003258 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003259 if (DEBUG_DISPATCH_CYCLE) {
3260 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003261 connection->getInputChannelName().c_str(),
3262 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 return;
3265 }
3266
3267 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003269 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003270 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003271 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003273 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003274 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003275 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3276 logDispatchStateLocked();
3277 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3278 "target on connection "
3279 << connection->getInputChannelName() << " for "
3280 << originalMotionEntry.getDescription();
3281 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003283 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3284 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 if (!splitMotionEntry) {
3286 return; // split event was dropped
3287 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003288 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3289 std::string reason = std::string("reason=pointer cancel on split window");
3290 android_log_event_list(LOGTAG_INPUT_CANCEL)
3291 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3292 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003293 if (DEBUG_FOCUS) {
3294 ALOGD("channel '%s' ~ Split motion event.",
3295 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003296 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003297 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003298 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3299 std::move(splitMotionEntry),
3300 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 return;
3302 }
3303 }
3304
3305 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003306 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3307 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308}
3309
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003310void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3311 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3312 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003313 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003314 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3315 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003316 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003317
hongzuo liu95785e22022-09-06 02:51:35 +00003318 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003320 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
3322 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003323 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 startDispatchCycleLocked(currentTime, connection);
3325 }
3326}
3327
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003328void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003329 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003330 const InputTarget& inputTarget) {
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003331 // TODO(b/210460522): Verify all targets excluding global monitors are associated with a window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 // This is a new event.
3333 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003334 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003335 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003337 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3338 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003339 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003341 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003342 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003343 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3344 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003345 LOG(WARNING) << "channel " << connection->getInputChannelName()
3346 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 return; // skip the inconsistent event
3348 }
3349 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003352 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003353 std::shared_ptr<const MotionEntry> resolvedMotion =
3354 std::static_pointer_cast<const MotionEntry>(eventEntry);
3355 {
3356 // Determine the resolved motion entry.
3357 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3358 int32_t resolvedAction = motionEntry.action;
3359 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003361 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003362 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003363 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003364 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003365 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003366 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003367 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003368 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003369 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003370 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3371 }
3372 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3373 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3374 motionEntry.displayId)) {
3375 if (DEBUG_DISPATCH_CYCLE) {
3376 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3377 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3378 "enter event";
3379 }
3380 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3381 }
3382
3383 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3384 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3385 }
3386 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3387 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3388 }
3389 if (dispatchEntry->targetFlags.test(
3390 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3391 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3392 }
3393
3394 dispatchEntry->resolvedFlags = resolvedFlags;
3395 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003396 std::optional<std::vector<PointerProperties>> usingProperties;
3397 std::optional<std::vector<PointerCoords>> usingCoords;
3398 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3399 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3400 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3401 // the dispatcher, and therefore the coordinates of this event are currently
3402 // incorrect. These events should use the coordinates of the last dispatched
3403 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3404 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3405 std::optional<std::pair<std::vector<PointerProperties>,
3406 std::vector<PointerCoords>>>
3407 pointerInfo =
3408 connection->inputState.getPointersOfLastEvent(motionEntry,
3409 hovering);
3410 if (pointerInfo) {
3411 usingProperties = pointerInfo->first;
3412 usingCoords = pointerInfo->second;
3413 }
3414 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003415 // Generate a new MotionEntry with a new eventId using the resolved action and
3416 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003417 resolvedMotion = std::make_shared<
3418 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3419 motionEntry.eventTime, motionEntry.deviceId,
3420 motionEntry.source, motionEntry.displayId,
3421 motionEntry.policyFlags, resolvedAction,
3422 motionEntry.actionButton, resolvedFlags,
3423 motionEntry.metaState, motionEntry.buttonState,
3424 motionEntry.classification, motionEntry.edgeFlags,
3425 motionEntry.xPrecision, motionEntry.yPrecision,
3426 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3427 motionEntry.downTime,
3428 usingProperties.value_or(motionEntry.pointerProperties),
3429 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003430 if (ATRACE_ENABLED()) {
3431 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3432 ") to MotionEvent(id=0x%" PRIx32 ").",
3433 motionEntry.id, resolvedMotion->id);
3434 ATRACE_NAME(message.c_str());
3435 }
3436
3437 // Set the resolved motion entry in the DispatchEntry.
3438 dispatchEntry->eventEntry = resolvedMotion;
3439 eventEntry = resolvedMotion;
3440 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003443 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3444 // devices being active at the same time in the same window, so if a new device is
3445 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003446 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003447 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003448 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003449 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003450 << connection->getInputChannelName() << " with event "
3451 << cancelEvent->getDescription();
3452 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3453 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003454 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003455
3456 // Send these cancel events to the queue before sending the event from the new
3457 // device.
3458 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3459 }
3460
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003461 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003462 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003463 LOG(WARNING) << "channel " << connection->getInputChannelName()
3464 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003465 return; // skip the inconsistent event
3466 }
3467
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003468 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3469 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003470 // Skip reporting pointer down outside focus to the policy.
3471 break;
3472 }
3473
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003474 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003475 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003476
3477 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003479 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003480 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003481 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3482 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003483 break;
3484 }
Chris Yef59a2f42020-10-16 12:55:26 -07003485 case EventEntry::Type::SENSOR: {
3486 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3487 break;
3488 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003489 case EventEntry::Type::CONFIGURATION_CHANGED:
3490 case EventEntry::Type::DEVICE_RESET: {
3491 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003492 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003493 break;
3494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 }
3496
3497 // Remember that we are waiting for this dispatch to complete.
3498 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003499 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501
3502 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003503 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003504 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003505}
3506
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003508 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003509 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003510 * The first role is to log input interaction with windows, which helps determine what the user was
3511 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3512 * that user started interacting with launcher window, as well as any other window that received
3513 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3514 * when the set of tokens that received the event changes. It is not logged again as long as the
3515 * user is interacting with the same windows.
3516 *
3517 * The second role is to track input device activity for metrics collection. For each input event,
3518 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3519 * input_interaction logs, the device interaction is reported even when the set of interaction
3520 * tokens do not change.
3521 *
3522 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3523 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003524 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003525void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3526 const std::vector<InputTarget>& targets) {
3527 int32_t deviceId;
3528 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003529 // Skip ACTION_UP events, and all events other than keys and motions
3530 if (entry.type == EventEntry::Type::KEY) {
3531 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3532 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3533 return;
3534 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003535 deviceId = keyEntry.deviceId;
3536 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003537 } else if (entry.type == EventEntry::Type::MOTION) {
3538 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3539 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003540 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3541 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003542 return;
3543 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003544 deviceId = motionEntry.deviceId;
3545 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003546 } else {
3547 return; // Not a key or a motion
3548 }
3549
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003550 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003551 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003552 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003553 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003554 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003555 continue; // Skip windows that receive ACTION_OUTSIDE
3556 }
3557
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003558 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003559 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003560 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003561 if (target.windowHandle) {
3562 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3563 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003564 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003565
3566 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3567 REQUIRES(mLock) {
3568 scoped_unlock unlock(mLock);
3569 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3570 };
3571 postCommandLocked(std::move(command));
3572
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003573 if (newConnectionTokens == mInteractionConnectionTokens) {
3574 return; // no change
3575 }
3576 mInteractionConnectionTokens = newConnectionTokens;
3577
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003578 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003579 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003580 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003582 std::string message = "Interaction with: " + targetList;
3583 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003584 message += "<none>";
3585 }
3586 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3587}
3588
chaviwfd6d3512019-03-25 13:23:49 -07003589void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003590 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003591 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003592 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3593 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003594 return;
3595 }
3596
Vishnu Nairc519ff72021-01-21 08:23:08 -08003597 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003598 if (focusedToken == token) {
3599 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003600 return;
3601 }
3602
Prabir Pradhancef936d2021-07-21 16:17:52 +00003603 auto command = [this, token]() REQUIRES(mLock) {
3604 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003605 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003606 };
3607 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608}
3609
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003610status_t InputDispatcher::publishMotionEvent(Connection& connection,
3611 DispatchEntry& dispatchEntry) const {
3612 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3613 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3614
3615 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003616 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003617
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003618 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003619 // Set the X and Y offset and X and Y scale depending on the input source.
3620 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003621 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003622 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3623 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003624 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625 scaledCoords[i] = motionEntry.pointerCoords[i];
3626 // Don't apply window scale here since we don't want scale to affect raw
3627 // coordinates. The scale will be sent back to the client and applied
3628 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003629 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003630 }
3631 usingCoords = scaledCoords;
3632 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003633 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003634 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003635 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003636 scaledCoords[i].clear();
3637 }
3638 usingCoords = scaledCoords;
3639 }
3640
3641 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3642
3643 // Publish the motion event.
3644 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003645 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3646 motionEntry.source, motionEntry.displayId, std::move(hmac),
3647 motionEntry.action, motionEntry.actionButton,
3648 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3649 motionEntry.metaState, motionEntry.buttonState,
3650 motionEntry.classification, dispatchEntry.transform,
3651 motionEntry.xPrecision, motionEntry.yPrecision,
3652 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3653 dispatchEntry.rawTransform, motionEntry.downTime,
3654 motionEntry.eventTime, motionEntry.getPointerCount(),
3655 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003656}
3657
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003659 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003660 ATRACE_NAME_IF(ATRACE_ENABLED(),
3661 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3662 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003663 if (DEBUG_DISPATCH_CYCLE) {
3664 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003667 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003668 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003670 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003671 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672
3673 // Publish the event.
3674 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3676 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003677 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003678 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3679 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003680 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003681 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3682 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003685 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003686 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003687 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3688 keyEntry.deviceId, keyEntry.source,
3689 keyEntry.displayId, std::move(hmac),
3690 keyEntry.action, dispatchEntry->resolvedFlags,
3691 keyEntry.keyCode, keyEntry.scanCode,
3692 keyEntry.metaState, keyEntry.repeatCount,
3693 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003694 if (mTracer) {
3695 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3696 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003700 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003701 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003702 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3703 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003704 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003705 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003706 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003707 if (mTracer) {
3708 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3709 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003710 break;
3711 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003712
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003713 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003714 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003715 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003717 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003718 break;
3719 }
3720
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003721 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3722 const TouchModeEntry& touchModeEntry =
3723 static_cast<const TouchModeEntry&>(eventEntry);
3724 status = connection->inputPublisher
3725 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3726 touchModeEntry.inTouchMode);
3727
3728 break;
3729 }
3730
Prabir Pradhan99987712020-11-10 18:43:05 -08003731 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3732 const auto& captureEntry =
3733 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3734 status = connection->inputPublisher
3735 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003736 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003737 break;
3738 }
3739
arthurhungb89ccb02020-12-30 16:19:01 +08003740 case EventEntry::Type::DRAG: {
3741 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3742 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3743 dragEntry.id, dragEntry.x,
3744 dragEntry.y,
3745 dragEntry.isExiting);
3746 break;
3747 }
3748
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003749 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003750 case EventEntry::Type::DEVICE_RESET:
3751 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003752 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003753 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757
3758 // Check the result.
3759 if (status) {
3760 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003761 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 "This is unexpected because the wait queue is empty, so the pipe "
3764 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003765 "event to it, status=%s(%d)",
3766 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3767 status);
Harry Cutts33476232023-01-30 19:57:29 +00003768 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 } else {
3770 // Pipe is full and we are waiting for the app to finish process some events
3771 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003772 if (DEBUG_DISPATCH_CYCLE) {
3773 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3774 "waiting for the application to catch up",
3775 connection->getInputChannelName().c_str());
3776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 }
3778 } else {
3779 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003780 "status=%s(%d)",
3781 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3782 status);
Harry Cutts33476232023-01-30 19:57:29 +00003783 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785 return;
3786 }
3787
3788 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003789 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3790 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3791 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003792 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003793 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003794 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003795 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003796 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798}
3799
chaviw09c8d2d2020-08-24 15:48:26 -07003800std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3801 size_t size;
3802 switch (event.type) {
3803 case VerifiedInputEvent::Type::KEY: {
3804 size = sizeof(VerifiedKeyEvent);
3805 break;
3806 }
3807 case VerifiedInputEvent::Type::MOTION: {
3808 size = sizeof(VerifiedMotionEvent);
3809 break;
3810 }
3811 }
3812 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3813 return mHmacKeyManager.sign(start, size);
3814}
3815
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003816const std::array<uint8_t, 32> InputDispatcher::getSignature(
3817 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003818 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003819 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003820 // Only sign events up and down events as the purely move events
3821 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003822 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003823 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003824
3825 VerifiedMotionEvent verifiedEvent =
3826 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3827 verifiedEvent.actionMasked = actionMasked;
3828 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3829 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003830}
3831
3832const std::array<uint8_t, 32> InputDispatcher::getSignature(
3833 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3834 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3835 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003836 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003837}
3838
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003840 const std::shared_ptr<Connection>& connection,
3841 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003842 if (DEBUG_DISPATCH_CYCLE) {
3843 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3844 connection->getInputChannelName().c_str(), seq, toString(handled));
3845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003847 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 return;
3849 }
3850
3851 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003852 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3853 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3854 };
3855 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856}
3857
3858void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003859 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003860 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003861 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003862 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3863 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
3866 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003867 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003868 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003869 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003870 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871
3872 // The connection appears to be unrecoverably broken.
3873 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003874 if (connection->status == Connection::Status::NORMAL) {
3875 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876
3877 if (notify) {
3878 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003879 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3880 connection->getInputChannelName().c_str());
3881
3882 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003883 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003884 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003885 };
3886 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 }
3888 }
3889}
3890
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003891void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003892 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003893 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003894 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 }
3896}
3897
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003898void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003900 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902}
3903
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003904int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3905 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003906 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003907 if (connection == nullptr) {
3908 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3909 connectionToken.get(), events);
3910 return 0; // remove the callback
3911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003913 bool notify;
3914 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3915 if (!(events & ALOOPER_EVENT_INPUT)) {
3916 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3917 "events=0x%x",
3918 connection->getInputChannelName().c_str(), events);
3919 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 }
3921
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003922 nsecs_t currentTime = now();
3923 bool gotOne = false;
3924 status_t status = OK;
3925 for (;;) {
3926 Result<InputPublisher::ConsumerResponse> result =
3927 connection->inputPublisher.receiveConsumerResponse();
3928 if (!result.ok()) {
3929 status = result.error().code();
3930 break;
3931 }
3932
3933 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3934 const InputPublisher::Finished& finish =
3935 std::get<InputPublisher::Finished>(*result);
3936 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3937 finish.consumeTime);
3938 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003939 if (shouldReportMetricsForConnection(*connection)) {
3940 const InputPublisher::Timeline& timeline =
3941 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003942 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3943 connection->getToken(),
3944 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003945 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003946 }
3947 gotOne = true;
3948 }
3949 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003950 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003951 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 return 1;
3953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
3955
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003956 notify = status != DEAD_OBJECT || !connection->monitor;
3957 if (notify) {
3958 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3959 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3960 status);
3961 }
3962 } else {
3963 // Monitor channels are never explicitly unregistered.
3964 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003965 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003966 notify = !connection->monitor && stillHaveWindowHandle;
3967 if (notify) {
3968 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3969 connection->getInputChannelName().c_str(), events);
3970 }
3971 }
3972
3973 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003974 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003975 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976}
3977
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003978void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003980 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003981 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983}
3984
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003986 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003987 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003988 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003989 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003990 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003991 }
3992}
3993
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003995 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00003996 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 return;
3998 }
3999
4000 nsecs_t currentTime = now();
4001
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004003 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004005 if (cancelationEvents.empty()) {
4006 return;
4007 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004008
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004009 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4010 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004011 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004012 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004013 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004014 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015
Arthur Hungb3307ee2021-10-14 10:57:37 +00004016 std::string reason = std::string("reason=").append(options.reason);
4017 android_log_event_list(LOGTAG_INPUT_CANCEL)
4018 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4019
hongzuo liu95785e22022-09-06 02:51:35 +00004020 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004021 // The target to use if we don't find a window associated with the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004022 const InputTarget fallbackTarget{.connection = connection};
4023 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004024
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004025 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004027 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004028
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004029 switch (cancelationEventEntry->type) {
4030 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004031 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004032 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4033 ? std::make_optional(keyEntry.displayId)
4034 : std::nullopt;
4035 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004036 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4037 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004038 } else {
4039 targets.emplace_back(fallbackTarget);
4040 }
4041 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004044 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004045 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004046 const std::optional<int32_t> targetDisplay =
4047 motionEntry.displayId != ADISPLAY_ID_NONE
4048 ? std::make_optional(motionEntry.displayId)
4049 : std::nullopt;
4050 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004051 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004052 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004053 pointerIndex++) {
4054 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4055 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004056 if (mDragState && mDragState->dragWindow->getToken() == token &&
4057 pointerIds.test(mDragState->pointerId)) {
4058 LOG(INFO) << __func__
4059 << ": Canceling drag and drop because the pointers for the drag "
4060 "window are being canceled.";
4061 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4062 mDragState.reset();
4063 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004064 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4065 ftl::Flags<InputTarget::Flags>(), pointerIds,
4066 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004067 } else {
4068 targets.emplace_back(fallbackTarget);
4069 const auto it = mDisplayInfos.find(motionEntry.displayId);
4070 if (it != mDisplayInfos.end()) {
4071 targets.back().displayTransform = it->second.transform;
4072 targets.back().setDefaultPointerTransform(it->second.transform);
4073 }
4074 }
4075 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004076 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004078 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004079 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004080 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4081 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004082 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004083 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004084 break;
4085 }
4086 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004087 case EventEntry::Type::DEVICE_RESET:
4088 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004089 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004090 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004091 break;
4092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 }
4094
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004095 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004096 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004098
hongzuo liu95785e22022-09-06 02:51:35 +00004099 // If the outbound queue was previously empty, start the dispatch cycle going.
4100 if (wasEmpty && !connection->outboundQueue.empty()) {
4101 startDispatchCycleLocked(currentTime, connection);
4102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103}
4104
Svet Ganov5d3bc372020-01-26 23:11:07 -08004105void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004106 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004107 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004108 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004109 return;
4110 }
4111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004113 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004114
4115 if (downEvents.empty()) {
4116 return;
4117 }
4118
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004119 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004120 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4121 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004122 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004123
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004124 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(connection->getToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004125
hongzuo liu95785e22022-09-06 02:51:35 +00004126 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004127 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004128 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004129 switch (downEventEntry->type) {
4130 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004131 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4132 if (windowHandle != nullptr) {
4133 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004134 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004135 pointerIndex++) {
4136 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4137 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004138 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4139 targetFlags, pointerIds, motionEntry.downTime,
4140 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004141 } else {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004142 targets.emplace_back(
4143 InputTarget{.connection = connection, .flags = targetFlags});
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004144 const auto it = mDisplayInfos.find(motionEntry.displayId);
4145 if (it != mDisplayInfos.end()) {
4146 targets.back().displayTransform = it->second.transform;
4147 targets.back().setDefaultPointerTransform(it->second.transform);
4148 }
4149 }
4150 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004151 break;
4152 }
4153
4154 case EventEntry::Type::KEY:
4155 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004156 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004157 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004158 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004159 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004160 case EventEntry::Type::SENSOR:
4161 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004162 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004163 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004164 break;
4165 }
4166 }
4167
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004168 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004169 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004170 }
4171
hongzuo liu95785e22022-09-06 02:51:35 +00004172 // If the outbound queue was previously empty, start the dispatch cycle going.
4173 if (wasEmpty && !connection->outboundQueue.empty()) {
4174 startDispatchCycleLocked(downTime, connection);
4175 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004176}
4177
Arthur Hungc539dbb2022-12-08 07:45:36 +00004178void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4179 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4180 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004181 std::shared_ptr<Connection> wallpaperConnection =
4182 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004183 if (wallpaperConnection != nullptr) {
4184 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4185 }
4186 }
4187}
4188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004189std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004190 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4191 nsecs_t splitDownTime) {
4192 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
4194 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004195 std::vector<PointerProperties> splitPointerProperties;
4196 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004198 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 uint32_t splitPointerCount = 0;
4200
4201 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004204 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004206 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004208 splitPointerProperties.push_back(pointerProperties);
4209 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 splitPointerCount += 1;
4211 }
4212 }
4213
4214 if (splitPointerCount != pointerIds.count()) {
4215 // This is bad. We are missing some of the pointers that we expected to deliver.
4216 // Most likely this indicates that we received an ACTION_MOVE events that has
4217 // different pointer ids than we expected based on the previous ACTION_DOWN
4218 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4219 // in this way.
4220 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004221 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004222 "a broken sequence of pointer ids from the input device: %s",
4223 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004224 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004227 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4230 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004231 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004233 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004235 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 if (pointerIds.count() == 1) {
4237 // The first/last pointer went down/up.
4238 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004240 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4241 ? AMOTION_EVENT_ACTION_CANCEL
4242 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 } else {
4244 // A secondary pointer went down/up.
4245 uint32_t splitPointerIndex = 0;
4246 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4247 splitPointerIndex += 1;
4248 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 action = maskedAction |
4250 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252 } else {
4253 // An unrelated pointer changed.
4254 action = AMOTION_EVENT_ACTION_MOVE;
4255 }
4256 }
4257
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004258 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4259 logDispatchStateLocked();
4260 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4261 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4262 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004263 }
4264
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004265 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004266 ATRACE_NAME_IF(ATRACE_ENABLED(),
4267 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4268 ").",
4269 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004271 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4272 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 originalMotionEntry.deviceId, originalMotionEntry.source,
4274 originalMotionEntry.displayId,
4275 originalMotionEntry.policyFlags, action,
4276 originalMotionEntry.actionButton,
4277 originalMotionEntry.flags, originalMotionEntry.metaState,
4278 originalMotionEntry.buttonState,
4279 originalMotionEntry.classification,
4280 originalMotionEntry.edgeFlags,
4281 originalMotionEntry.xPrecision,
4282 originalMotionEntry.yPrecision,
4283 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004284 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004285 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 return splitMotionEntry;
4288}
4289
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004290void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4291 std::scoped_lock _l(mLock);
4292 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4293}
4294
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004295void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004296 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004297 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Antonio Kantekf16f2832021-09-28 04:39:20 +00004300 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004302 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004304 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004305 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004306 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 } // release lock
4308
4309 if (needWake) {
4310 mLooper->wake();
4311 }
4312}
4313
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004315 ALOGD_IF(debugInboundEventDetails(),
4316 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4317 ", deviceId=%d, source=%s, displayId=%" PRId32
4318 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4319 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004320 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4321 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4322 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004323 Result<void> keyCheck = validateKeyEvent(args.action);
4324 if (!keyCheck.ok()) {
4325 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 return;
4327 }
4328
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004329 uint32_t policyFlags = args.policyFlags;
4330 int32_t flags = args.flags;
4331 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004332 // InputDispatcher tracks and generates key repeats on behalf of
4333 // whatever notifies it, so repeatCount should always be set to 0
4334 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4336 policyFlags |= POLICY_FLAG_VIRTUAL;
4337 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 if (policyFlags & POLICY_FLAG_FUNCTION) {
4340 metaState |= AMETA_FUNCTION_ON;
4341 }
4342
4343 policyFlags |= POLICY_FLAG_TRUSTED;
4344
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004345 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004347 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4348 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4349 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
Michael Wright2b3c3302018-03-02 17:19:13 +00004351 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004352 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004353 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4354 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Antonio Kantekf16f2832021-09-28 04:39:20 +00004358 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 { // acquire lock
4360 mLock.lock();
4361
4362 if (shouldSendKeyToInputFilterLocked(args)) {
4363 mLock.unlock();
4364
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004365 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004366 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 return; // event was consumed by the filter
4368 }
4369
4370 mLock.lock();
4371 }
4372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004374 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4375 args.deviceId, args.source, args.displayId, policyFlags,
4376 args.action, flags, keyCode, args.scanCode, metaState,
4377 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004378 if (mTracer) {
4379 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 mLock.unlock();
4384 } // release lock
4385
4386 if (needWake) {
4387 mLooper->wake();
4388 }
4389}
4390
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 return mInputFilterEnabled;
4393}
4394
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004395void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004396 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004397 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004398 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004399 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004400 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4401 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004402 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4403 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4404 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4405 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4406 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004407 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004408 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4409 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004410 i, args.pointerProperties[i].id,
4411 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4412 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4413 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4414 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4415 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4416 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4417 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4418 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4419 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4420 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004423
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004424 Result<void> motionCheck =
4425 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4426 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004427 if (!motionCheck.ok()) {
4428 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4429 return;
4430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004432 if (DEBUG_VERIFY_EVENTS) {
4433 auto [it, _] =
4434 mVerifiersByDisplay.try_emplace(args.displayId,
4435 StringPrintf("display %" PRId32, args.displayId));
4436 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004437 it->second.processMovement(args.deviceId, args.source, args.action,
4438 args.getPointerCount(), args.pointerProperties.data(),
4439 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004440 if (!result.ok()) {
4441 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4442 }
4443 }
4444
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004445 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004447
4448 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004449 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4450 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004451 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4452 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004453 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
Antonio Kantekf16f2832021-09-28 04:39:20 +00004456 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 { // acquire lock
4458 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004459 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4460 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4461 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004463 if (touchStateIt != mTouchStatesByDisplay.end()) {
4464 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004465 if (touchState.hasTouchingPointers(args.deviceId) ||
4466 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004467 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4468 }
4469 }
4470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471
4472 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004473 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004474 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004475 displayTransform = it->second.transform;
4476 }
4477
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 mLock.unlock();
4479
4480 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4482 args.action, args.actionButton, args.flags, args.edgeFlags,
4483 args.metaState, args.buttonState, args.classification,
4484 displayTransform, args.xPrecision, args.yPrecision,
4485 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004486 args.downTime, args.eventTime, args.getPointerCount(),
4487 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
4489 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004490 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 return; // event was consumed by the filter
4492 }
4493
4494 mLock.lock();
4495 }
4496
4497 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004498 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004499 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4500 args.deviceId, args.source, args.displayId,
4501 policyFlags, args.action, args.actionButton,
4502 args.flags, args.metaState, args.buttonState,
4503 args.classification, args.edgeFlags, args.xPrecision,
4504 args.yPrecision, args.xCursorPosition,
4505 args.yCursorPosition, args.downTime,
4506 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004507 if (mTracer) {
4508 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004511 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4512 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004513 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004515 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4516 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4517 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004518 }
4519
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004520 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 mLock.unlock();
4522 } // release lock
4523
4524 if (needWake) {
4525 mLooper->wake();
4526 }
4527}
4528
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004529void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004530 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004531 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4532 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533 args.id, args.eventTime, args.deviceId, args.source,
4534 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004535 }
Chris Yef59a2f42020-10-16 12:55:26 -07004536
Antonio Kantekf16f2832021-09-28 04:39:20 +00004537 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004538 { // acquire lock
4539 mLock.lock();
4540
4541 // Just enqueue a new sensor event.
4542 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004543 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4544 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4545 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004546
4547 needWake = enqueueInboundEventLocked(std::move(newEntry));
4548 mLock.unlock();
4549 } // release lock
4550
4551 if (needWake) {
4552 mLooper->wake();
4553 }
4554}
4555
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004556void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004557 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004558 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4559 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004560 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004561 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004562}
4563
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004564bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004565 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566}
4567
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004568void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004569 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004570 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4571 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004572 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004575 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004577 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578}
4579
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004580void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004581 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004582 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4583 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
Antonio Kantekf16f2832021-09-28 04:39:20 +00004586 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004588 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004590 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004591 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004592 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004593
4594 for (auto& [_, verifier] : mVerifiersByDisplay) {
4595 verifier.resetDevice(args.deviceId);
4596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 } // release lock
4598
4599 if (needWake) {
4600 mLooper->wake();
4601 }
4602}
4603
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004604void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004605 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004606 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4607 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004608 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004609
Antonio Kantekf16f2832021-09-28 04:39:20 +00004610 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004611 { // acquire lock
4612 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613 auto entry =
4614 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004615 needWake = enqueueInboundEventLocked(std::move(entry));
4616 } // release lock
4617
4618 if (needWake) {
4619 mLooper->wake();
4620 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004621}
4622
Prabir Pradhan5735a322022-04-11 17:23:34 +00004623InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004624 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004625 InputEventInjectionSync syncMode,
4626 std::chrono::milliseconds timeout,
4627 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004628 Result<void> eventValidation = validateInputEvent(*event);
4629 if (!eventValidation.ok()) {
4630 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4631 return InputEventInjectionResult::FAILED;
4632 }
4633
Prabir Pradhan65613802023-02-22 23:36:58 +00004634 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004635 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4636 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4637 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4638 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004639 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004640 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641
Prabir Pradhan5735a322022-04-11 17:23:34 +00004642 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004644 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004645 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4646 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4647 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4648 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4649 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004650 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004651 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004652 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004653 }
4654
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004655 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4656 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4657
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004660 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004661 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004662 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004663 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004664 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4665 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4666 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004667 int32_t keyCode = incomingKey.getKeyCode();
4668 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004669 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004670 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004671 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4672 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4673 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4676 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004677 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004678
4679 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4680 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004681 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4683 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4684 std::to_string(t.duration().count()).c_str());
4685 }
4686 }
4687
4688 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004689 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004690 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4691 incomingKey.getEventTime(), resolvedDeviceId,
4692 incomingKey.getSource(), incomingKey.getDisplayId(),
4693 policyFlags, action, flags, keyCode,
4694 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004695 incomingKey.getRepeatCount(),
4696 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004697 if (mTracer) {
4698 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4699 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004700 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 }
4703
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004704 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004705 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004706 const bool isPointerEvent =
4707 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4708 // If a pointer event has no displayId specified, inject it to the default display.
4709 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4710 ? ADISPLAY_ID_DEFAULT
4711 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004712 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713
4714 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004715 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004717 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4718 motionEvent.getAction(), eventTime,
4719 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4721 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4722 std::to_string(t.duration().count()).c_str());
4723 }
4724 }
4725
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004726 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4727 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4728 }
4729
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004731 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004732 const size_t pointerCount = motionEvent.getPointerCount();
4733 const std::vector<PointerProperties>
4734 pointerProperties(motionEvent.getPointerProperties(),
4735 motionEvent.getPointerProperties() + pointerCount);
4736
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004737 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004738 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004739 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4740 *sampleEventTimes, resolvedDeviceId,
4741 motionEvent.getSource(), displayId, policyFlags,
4742 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004743 motionEvent.getActionButton(), flags,
4744 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004745 motionEvent.getButtonState(),
4746 motionEvent.getClassification(),
4747 motionEvent.getEdgeFlags(),
4748 motionEvent.getXPrecision(),
4749 motionEvent.getYPrecision(),
4750 motionEvent.getRawXCursorPosition(),
4751 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004752 motionEvent.getDownTime(), pointerProperties,
4753 std::vector<PointerCoords>(samplePointerCoords,
4754 samplePointerCoords +
4755 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004756 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004757 if (mTracer) {
4758 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4759 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004760 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004761 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004762 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004763 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004764 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004765 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4766 resolvedDeviceId, motionEvent.getSource(), displayId,
4767 policyFlags, motionEvent.getAction(),
4768 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004769 motionEvent.getMetaState(), motionEvent.getButtonState(),
4770 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4771 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4772 motionEvent.getRawXCursorPosition(),
4773 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4774 pointerProperties,
4775 std::vector<PointerCoords>(samplePointerCoords,
4776 samplePointerCoords +
4777 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004778 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4779 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004780 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 }
4782 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004786 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004787 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
4789
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004791 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004792 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004793 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004794 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004795 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004796 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798
4799 mLock.unlock();
4800
4801 if (needWake) {
4802 mLooper->wake();
4803 }
4804
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004807 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 if (syncMode == InputEventInjectionSync::NONE) {
4810 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 } else {
4812 for (;;) {
4813 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004814 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 break;
4816 }
4817
4818 nsecs_t remainingTimeout = endTime - now();
4819 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004820 if (DEBUG_INJECTION) {
4821 ALOGD("injectInputEvent - Timed out waiting for injection result "
4822 "to become available.");
4823 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004824 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 break;
4826 }
4827
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004828 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 }
4830
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004831 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4832 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004834 if (DEBUG_INJECTION) {
4835 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4836 injectionState->pendingForegroundDispatches);
4837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 nsecs_t remainingTimeout = endTime - now();
4839 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004840 if (DEBUG_INJECTION) {
4841 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4842 "dispatches to finish.");
4843 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 break;
4846 }
4847
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004848 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
4850 }
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 } // release lock
4853
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004854 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004855 LOG(INFO) << "injectInputEvent - Finished with result "
4856 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858
4859 return injectionResult;
4860}
4861
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004862std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004863 std::array<uint8_t, 32> calculatedHmac;
4864 std::unique_ptr<VerifiedInputEvent> result;
4865 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004866 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004867 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4868 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4869 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004870 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004871 break;
4872 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004873 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004874 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4875 VerifiedMotionEvent verifiedMotionEvent =
4876 verifiedMotionEventFromMotionEvent(motionEvent);
4877 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004878 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004879 break;
4880 }
4881 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004882 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004883 return nullptr;
4884 }
4885 }
4886 if (calculatedHmac == INVALID_HMAC) {
4887 return nullptr;
4888 }
tyiu1573a672023-02-21 22:38:32 +00004889 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004890 return nullptr;
4891 }
4892 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004893}
4894
Prabir Pradhan24047542023-11-02 17:14:59 +00004895void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004896 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004897 if (!entry.injectionState) {
4898 // Not an injected event.
4899 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004901
4902 InjectionState& injectionState = *entry.injectionState;
4903 if (DEBUG_INJECTION) {
4904 LOG(INFO) << "Setting input event injection result to "
4905 << ftl::enum_string(injectionResult);
4906 }
4907
4908 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4909 // Log the outcome since the injector did not wait for the injection result.
4910 switch (injectionResult) {
4911 case InputEventInjectionResult::SUCCEEDED:
4912 ALOGV("Asynchronous input event injection succeeded.");
4913 break;
4914 case InputEventInjectionResult::TARGET_MISMATCH:
4915 ALOGV("Asynchronous input event injection target mismatch.");
4916 break;
4917 case InputEventInjectionResult::FAILED:
4918 ALOGW("Asynchronous input event injection failed.");
4919 break;
4920 case InputEventInjectionResult::TIMED_OUT:
4921 ALOGW("Asynchronous input event injection timed out.");
4922 break;
4923 case InputEventInjectionResult::PENDING:
4924 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4925 break;
4926 }
4927 }
4928
4929 injectionState.injectionResult = injectionResult;
4930 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931}
4932
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004933void InputDispatcher::transformMotionEntryForInjectionLocked(
4934 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004935 // Input injection works in the logical display coordinate space, but the input pipeline works
4936 // display space, so we need to transform the injected events accordingly.
4937 const auto it = mDisplayInfos.find(entry.displayId);
4938 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004939 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004940
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004941 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4942 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4943 const vec2 cursor =
4944 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4945 {entry.xCursorPosition, entry.yCursorPosition});
4946 entry.xCursorPosition = cursor.x;
4947 entry.yCursorPosition = cursor.y;
4948 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004949 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004950 entry.pointerCoords[i] =
4951 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4952 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004953 }
4954}
4955
Prabir Pradhan24047542023-11-02 17:14:59 +00004956void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004957 if (entry.injectionState) {
4958 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960}
4961
Prabir Pradhan24047542023-11-02 17:14:59 +00004962void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004963 if (entry.injectionState) {
4964 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004966 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004967 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 }
4969 }
4970}
4971
chaviw98318de2021-05-19 16:45:23 -05004972const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004973 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004974 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004975 auto it = mWindowHandlesByDisplay.find(displayId);
4976 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004977}
4978
chaviw98318de2021-05-19 16:45:23 -05004979sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004980 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004981 if (windowHandleToken == nullptr) {
4982 return nullptr;
4983 }
4984
Prabir Pradhan16463382023-10-12 23:03:19 +00004985 if (!displayId) {
4986 // Look through all displays.
4987 for (auto& it : mWindowHandlesByDisplay) {
4988 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4989 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4990 if (windowHandle->getToken() == windowHandleToken) {
4991 return windowHandle;
4992 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004995 return nullptr;
4996 }
4997
Prabir Pradhan16463382023-10-12 23:03:19 +00004998 // Only look through the requested display.
4999 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005000 if (windowHandle->getToken() == windowHandleToken) {
5001 return windowHandle;
5002 }
5003 }
5004 return nullptr;
5005}
5006
chaviw98318de2021-05-19 16:45:23 -05005007sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5008 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005009 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005010 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5011 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005012 if (handle->getId() == windowHandle->getId() &&
5013 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005014 if (windowHandle->getInfo()->displayId != it.first) {
5015 ALOGE("Found window %s in display %" PRId32
5016 ", but it should belong to display %" PRId32,
5017 windowHandle->getName().c_str(), it.first,
5018 windowHandle->getInfo()->displayId);
5019 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005020 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 }
5023 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005024 return nullptr;
5025}
5026
chaviw98318de2021-05-19 16:45:23 -05005027sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005028 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5029 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030}
5031
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005032ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5033 auto displayInfoIt = mDisplayInfos.find(displayId);
5034 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5035 : kIdentityTransform;
5036}
5037
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005038bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5039 const MotionEntry& motionEntry) const {
5040 const WindowInfo& info = *window->getInfo();
5041
5042 // Skip spy window targets that are not valid for targeted injection.
5043 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005044 return false;
5045 }
5046
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005047 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5048 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5049 return false;
5050 }
5051
5052 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5053 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5054 window->getName().c_str());
5055 return false;
5056 }
5057
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005058 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005059 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005060 ALOGW("Not sending touch to %s because there's no corresponding connection",
5061 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005062 return false;
5063 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005064
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005065 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005066 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005067 return false;
5068 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005069
5070 // Drop events that can't be trusted due to occlusion
5071 const auto [x, y] = resolveTouchedPosition(motionEntry);
5072 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5073 if (!isTouchTrustedLocked(occlusionInfo)) {
5074 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005075 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005076 for (const auto& log : occlusionInfo.debugInfo) {
5077 ALOGD("%s", log.c_str());
5078 }
5079 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005080 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5081 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005082 return false;
5083 }
5084
5085 // Drop touch events if requested by input feature
5086 if (shouldDropInput(motionEntry, window)) {
5087 return false;
5088 }
5089
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005090 // Ignore touches if stylus is down anywhere on screen
5091 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5092 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5093 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5094 return false;
5095 }
5096
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005097 return true;
5098}
5099
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005100void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005101 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5102 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005103 // Remove all handles on a display if there are no windows left.
5104 mWindowHandlesByDisplay.erase(displayId);
5105 return;
5106 }
5107
5108 // Since we compare the pointer of input window handles across window updates, we need
5109 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005110 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5111 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5112 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005113 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005114 }
5115
chaviw98318de2021-05-19 16:45:23 -05005116 std::vector<sp<WindowInfoHandle>> newHandles;
5117 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005118 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005119 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005120 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005121 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005122 const bool canReceiveInput =
5123 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5124 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005125 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005126 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005127 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005128 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005129 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005130 }
5131
5132 if (info->displayId != displayId) {
5133 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5134 handle->getName().c_str(), displayId, info->displayId);
5135 continue;
5136 }
5137
Robert Carredd13602020-04-13 17:24:34 -07005138 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5139 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005140 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005141 oldHandle->updateFrom(handle);
5142 newHandles.push_back(oldHandle);
5143 } else {
5144 newHandles.push_back(handle);
5145 }
5146 }
5147
5148 // Insert or replace
5149 mWindowHandlesByDisplay[displayId] = newHandles;
5150}
5151
Arthur Hungb92218b2018-08-14 12:00:21 +08005152/**
5153 * Called from InputManagerService, update window handle list by displayId that can receive input.
5154 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5155 * If set an empty list, remove all handles from the specific display.
5156 * For focused handle, check if need to change and send a cancel event to previous one.
5157 * For removed handle, check if need to send a cancel event if already in touch.
5158 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005159void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005160 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005161 if (DEBUG_FOCUS) {
5162 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005163 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005164 windowList += iwh->getName() + " ";
5165 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005166 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168
Prabir Pradhand65552b2021-10-07 11:23:50 -07005169 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005170 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005171 const WindowInfo& info = *window->getInfo();
5172
5173 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005174 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005175 if (noInputWindow && window->getToken() != nullptr) {
5176 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5177 window->getName().c_str());
5178 window->releaseChannel();
5179 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005180
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005181 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005182 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5183 !info.inputConfig.test(
5184 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005185 "%s has feature SPY, but is not a trusted overlay.",
5186 window->getName().c_str());
5187
Prabir Pradhand65552b2021-10-07 11:23:50 -07005188 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005189 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5190 !info.inputConfig.test(
5191 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005192 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5193 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005194 }
5195
Arthur Hung72d8dc32020-03-28 00:48:39 +00005196 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005197 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198
chaviw98318de2021-05-19 16:45:23 -05005199 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005200
chaviw98318de2021-05-19 16:45:23 -05005201 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005202
Vishnu Nairc519ff72021-01-21 08:23:08 -08005203 std::optional<FocusResolver::FocusChanges> changes =
5204 mFocusResolver.setInputWindows(displayId, windowHandles);
5205 if (changes) {
5206 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005209 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5210 mTouchStatesByDisplay.find(displayId);
5211 if (stateIt != mTouchStatesByDisplay.end()) {
5212 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005213 for (size_t i = 0; i < state.windows.size();) {
5214 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005215 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005216 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5217 << " in display %" << displayId;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005218 std::shared_ptr<Connection> touchedConnection =
5219 getConnectionLocked(touchedWindow.windowHandle->getToken());
5220 if (touchedConnection != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005221 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005222 "touched window was removed");
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005223 synthesizeCancelationEventsForConnectionLocked(touchedConnection, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005224 // Since we are about to drop the touch, cancel the events for the wallpaper as
5225 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005226 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005227 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5228 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005229 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005230 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005233 state.windows.erase(state.windows.begin() + i);
5234 } else {
5235 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 }
5237 }
arthurhungb89ccb02020-12-30 16:19:01 +08005238
arthurhung6d4bed92021-03-17 11:59:33 +08005239 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005240 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005241 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005242 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005243 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005244 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5245 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005246 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005247 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005248 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005249
Arthur Hung72d8dc32020-03-28 00:48:39 +00005250 // Release information for windows that are no longer present.
5251 // This ensures that unused input channels are released promptly.
5252 // Otherwise, they might stick around until the window handle is destroyed
5253 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005254 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005255 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005256 if (DEBUG_FOCUS) {
5257 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005258 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005259 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005260 }
chaviw291d88a2019-02-14 10:33:58 -08005261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262}
5263
5264void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005265 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005266 if (DEBUG_FOCUS) {
5267 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5268 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5269 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005271 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005272 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 } // release lock
5274
5275 // Wake up poll loop since it may need to make new input dispatching choices.
5276 mLooper->wake();
5277}
5278
Vishnu Nair599f1412021-06-21 10:39:58 -07005279void InputDispatcher::setFocusedApplicationLocked(
5280 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5281 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5282 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5283
5284 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5285 return; // This application is already focused. No need to wake up or change anything.
5286 }
5287
5288 // Set the new application handle.
5289 if (inputApplicationHandle != nullptr) {
5290 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5291 } else {
5292 mFocusedApplicationHandlesByDisplay.erase(displayId);
5293 }
5294
5295 // No matter what the old focused application was, stop waiting on it because it is
5296 // no longer focused.
5297 resetNoFocusedWindowTimeoutLocked();
5298}
5299
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005300void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5301 if (interval.count() < 0) {
5302 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5303 }
5304 std::scoped_lock _l(mLock);
5305 mMinTimeBetweenUserActivityPokes = interval;
5306}
5307
Tiger Huang721e26f2018-07-24 22:26:19 +08005308/**
5309 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5310 * the display not specified.
5311 *
5312 * We track any unreleased events for each window. If a window loses the ability to receive the
5313 * released event, we will send a cancel event to it. So when the focused display is changed, we
5314 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5315 * display. The display-specified events won't be affected.
5316 */
5317void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005318 if (DEBUG_FOCUS) {
5319 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5320 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005321 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005322 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005323
5324 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005325 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005326 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005327 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005328 std::shared_ptr<Connection> connection = getConnectionLocked(oldFocusedWindowToken);
5329 if (connection != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005330 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005331 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005332 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005333 options.displayId = ADISPLAY_ID_NONE;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005334 synthesizeCancelationEventsForConnectionLocked(connection, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005335 }
5336 }
5337 mFocusedDisplayId = displayId;
5338
Chris Ye3c2d6f52020-08-09 10:39:48 -07005339 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005340 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005341 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005342
Vishnu Nairad321cd2020-08-20 16:40:21 -07005343 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005344 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005345 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005346 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005347 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005348 }
5349 }
5350 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005351 } // release lock
5352
5353 // Wake up poll loop since it may need to make new input dispatching choices.
5354 mLooper->wake();
5355}
5356
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005358 if (DEBUG_FOCUS) {
5359 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
5362 bool changed;
5363 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005364 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365
5366 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5367 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005368 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 }
5370
5371 if (mDispatchEnabled && !enabled) {
5372 resetAndDropEverythingLocked("dispatcher is being disabled");
5373 }
5374
5375 mDispatchEnabled = enabled;
5376 mDispatchFrozen = frozen;
5377 changed = true;
5378 } else {
5379 changed = false;
5380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 } // release lock
5382
5383 if (changed) {
5384 // Wake up poll loop since it may need to make new input dispatching choices.
5385 mLooper->wake();
5386 }
5387}
5388
5389void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005390 if (DEBUG_FOCUS) {
5391 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393
5394 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005395 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
5397 if (mInputFilterEnabled == enabled) {
5398 return;
5399 }
5400
5401 mInputFilterEnabled = enabled;
5402 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5403 } // release lock
5404
5405 // Wake up poll loop since there might be work to do to drop everything.
5406 mLooper->wake();
5407}
5408
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005409bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005410 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005411 bool needWake = false;
5412 {
5413 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005414 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005415 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005416 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005417 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5418 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005419 mTouchModePerDisplay.count(displayId) == 0
5420 ? "not set"
5421 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5422
Antonio Kantek15beb512022-06-13 22:35:41 +00005423 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5424 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005425 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005426 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005427 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005428 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5429 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005430 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005431 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005432 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005433 return false;
5434 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005435 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005436 mTouchModePerDisplay[displayId] = inTouchMode;
5437 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5438 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005439 needWake = enqueueInboundEventLocked(std::move(entry));
5440 } // release lock
5441
5442 if (needWake) {
5443 mLooper->wake();
5444 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005445 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005446}
5447
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005448bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005449 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5450 if (focusedToken == nullptr) {
5451 return false;
5452 }
5453 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5454 return isWindowOwnedBy(windowHandle, pid, uid);
5455}
5456
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005457bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005458 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5459 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5460 const sp<WindowInfoHandle> windowHandle =
5461 getWindowHandleLocked(connectionToken);
5462 return isWindowOwnedBy(windowHandle, pid, uid);
5463 }) != mInteractionConnectionTokens.end();
5464}
5465
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005466void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5467 if (opacity < 0 || opacity > 1) {
5468 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5469 return;
5470 }
5471
5472 std::scoped_lock lock(mLock);
5473 mMaximumObscuringOpacityForTouch = opacity;
5474}
5475
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005476std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5477InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005478 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5479 for (TouchedWindow& w : state.windows) {
5480 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005481 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005482 }
5483 }
5484 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005485 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005486}
5487
arthurhungb89ccb02020-12-30 16:19:01 +08005488bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5489 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005490 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005491 if (DEBUG_FOCUS) {
5492 ALOGD("Trivial transfer to same window.");
5493 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005494 return true;
5495 }
5496
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499
Arthur Hungabbb9d82021-09-01 14:52:30 +00005500 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005501 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005502
Arthur Hungabbb9d82021-09-01 14:52:30 +00005503 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005504 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 return false;
5506 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005507 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5508 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005509 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5510 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005511 return false;
5512 }
5513 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005514
Arthur Hungabbb9d82021-09-01 14:52:30 +00005515 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5516 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005517 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005518 return false;
5519 }
5520
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005521 if (DEBUG_FOCUS) {
5522 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005523 touchedWindow->windowHandle->getName().c_str(),
5524 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
5526
Arthur Hungabbb9d82021-09-01 14:52:30 +00005527 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005528 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005529 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005530 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005531 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532
Arthur Hungabbb9d82021-09-01 14:52:30 +00005533 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005534 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005535 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005536 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005537 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005538 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005539 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005540 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005541 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
Arthur Hungabbb9d82021-09-01 14:52:30 +00005543 // Store the dragging window.
5544 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005545 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005546 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5547 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005548 return false;
5549 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005550 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005551 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005552 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 }
5554
Arthur Hungabbb9d82021-09-01 14:52:30 +00005555 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005556 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5557 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005558 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005559 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005560 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5561 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005563 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5564 newTargetFlags);
5565
5566 // Check if the wallpaper window should deliver the corresponding event.
5567 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005568 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 } // release lock
5571
5572 // Wake up poll loop since it may need to make new input dispatching choices.
5573 mLooper->wake();
5574 return true;
5575}
5576
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005577/**
5578 * Get the touched foreground window on the given display.
5579 * Return null if there are no windows touched on that display, or if more than one foreground
5580 * window is being touched.
5581 */
5582sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5583 auto stateIt = mTouchStatesByDisplay.find(displayId);
5584 if (stateIt == mTouchStatesByDisplay.end()) {
5585 ALOGI("No touch state on display %" PRId32, displayId);
5586 return nullptr;
5587 }
5588
5589 const TouchState& state = stateIt->second;
5590 sp<WindowInfoHandle> touchedForegroundWindow;
5591 // If multiple foreground windows are touched, return nullptr
5592 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005593 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005594 if (touchedForegroundWindow != nullptr) {
5595 ALOGI("Two or more foreground windows: %s and %s",
5596 touchedForegroundWindow->getName().c_str(),
5597 window.windowHandle->getName().c_str());
5598 return nullptr;
5599 }
5600 touchedForegroundWindow = window.windowHandle;
5601 }
5602 }
5603 return touchedForegroundWindow;
5604}
5605
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005606// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005607bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005608 sp<IBinder> fromToken;
5609 { // acquire lock
5610 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005612 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005613 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5614 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005615 return false;
5616 }
5617
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005618 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5619 if (from == nullptr) {
5620 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5621 return false;
5622 }
5623
5624 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005625 } // release lock
5626
5627 return transferTouchFocus(fromToken, destChannelToken);
5628}
5629
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005631 if (DEBUG_FOCUS) {
5632 ALOGD("Resetting and dropping all events (%s).", reason);
5633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634
Michael Wrightfb04fd52022-11-24 22:31:11 +00005635 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 synthesizeCancelationEventsForAllConnectionsLocked(options);
5637
5638 resetKeyRepeatLocked();
5639 releasePendingEventLocked();
5640 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005641 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005643 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005644 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645}
5646
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005647void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005648 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 dumpDispatchStateLocked(dump);
5650
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005651 std::istringstream stream(dump);
5652 std::string line;
5653
5654 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005655 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 }
5657}
5658
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005659std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005660 std::string dump;
5661
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005662 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5663 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005664
5665 std::string windowName = "None";
5666 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005667 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005668 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5669 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5670 : "token has capture without window";
5671 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005672 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005673
5674 return dump;
5675}
5676
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005677void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005678 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5679 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5680 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005681 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682
Tiger Huang721e26f2018-07-24 22:26:19 +08005683 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5684 dump += StringPrintf(INDENT "FocusedApplications:\n");
5685 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5686 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005687 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005688 const std::chrono::duration timeout =
5689 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005690 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005691 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005692 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005695 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005697
Vishnu Nairc519ff72021-01-21 08:23:08 -08005698 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005701 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005703 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005704 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5705 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
5707 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005708 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 }
5710
arthurhung6d4bed92021-03-17 11:59:33 +08005711 if (mDragState) {
5712 dump += StringPrintf(INDENT "DragState:\n");
5713 mDragState->dump(dump, INDENT2);
5714 }
5715
Arthur Hungb92218b2018-08-14 12:00:21 +08005716 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005717 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5718 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5719 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5720 const auto& displayInfo = it->second;
5721 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5722 displayInfo.logicalHeight);
5723 displayInfo.transform.dump(dump, "transform", INDENT4);
5724 } else {
5725 dump += INDENT2 "No DisplayInfo found!\n";
5726 }
5727
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005728 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005729 dump += INDENT2 "Windows:\n";
5730 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005731 dump += StringPrintf(INDENT3 "%zu: %s", i,
5732 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005733 }
5734 } else {
5735 dump += INDENT2 "Windows: <none>\n";
5736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005739 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005742 if (!mGlobalMonitorsByDisplay.empty()) {
5743 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5744 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005745 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
5750
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005751 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752
5753 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005754 if (!mRecentQueue.empty()) {
5755 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005756 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005757 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005758 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005759 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
5761 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005762 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 }
5764
5765 // Dump event currently being dispatched.
5766 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005767 dump += INDENT "PendingEvent:\n";
5768 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005769 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005770 dump += StringPrintf(", age=%" PRId64 "ms\n",
5771 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005773 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 }
5775
5776 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005777 if (!mInboundQueue.empty()) {
5778 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005779 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005780 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005781 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005782 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005785 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 }
5787
Prabir Pradhancef936d2021-07-21 16:17:52 +00005788 if (!mCommandQueue.empty()) {
5789 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5790 } else {
5791 dump += INDENT "CommandQueue: <empty>\n";
5792 }
5793
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005794 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005795 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005796 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005797 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005798 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005799 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005800 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005801 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005802 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005804 if (!connection->outboundQueue.empty()) {
5805 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5806 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005807 dump += dumpQueue(connection->outboundQueue, currentTime);
5808
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005810 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 }
5812
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005813 if (!connection->waitQueue.empty()) {
5814 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5815 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005816 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005818 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005820 std::string inputStateDump = streamableToString(connection->inputState);
5821 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005822 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005823 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 }
5826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829
Antonio Kantek15beb512022-06-13 22:35:41 +00005830 if (!mTouchModePerDisplay.empty()) {
5831 dump += INDENT "TouchModePerDisplay:\n";
5832 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5833 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5834 std::to_string(touchMode).c_str());
5835 }
5836 } else {
5837 dump += INDENT "TouchModePerDisplay: <none>\n";
5838 }
5839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005840 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005841 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5842 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5843 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005844 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005845 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005846 dump += INDENT "InputTracer: ";
5847 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848}
5849
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005850void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005851 const size_t numMonitors = monitors.size();
5852 for (size_t i = 0; i < numMonitors; i++) {
5853 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005854 const std::shared_ptr<Connection>& connection = monitor.connection;
5855 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005856 dump += "\n";
5857 }
5858}
5859
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005860class LooperEventCallback : public LooperCallback {
5861public:
5862 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5863 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5864
5865private:
5866 std::function<int(int events)> mCallback;
5867};
5868
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005869Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005870 if (DEBUG_CHANNEL_CREATION) {
5871 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005874 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005875 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005876 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005877
5878 if (result) {
5879 return base::Error(result) << "Failed to open input channel pair with name " << name;
5880 }
5881
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005883 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005884 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005885 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005886 std::shared_ptr<Connection> connection =
5887 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5888 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005890 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5891 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005892 ALOGE("Created a new connection, but the token %p is already known", token.get());
5893 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005894
5895 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5896 this, std::placeholders::_1, token);
5897
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005898 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005899 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 } // release lock
5901
5902 // Wake the looper because some connections have changed.
5903 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005904 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905}
5906
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005907Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005908 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005909 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005910 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005911 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005912 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005913 if (result) {
5914 return base::Error(result) << "Failed to open input channel pair with name " << name;
5915 }
5916
Michael Wright3dd60e22019-03-27 22:06:44 +00005917 { // acquire lock
5918 std::scoped_lock _l(mLock);
5919
5920 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005921 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5922 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005923 }
5924
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005925 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005926 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005927 std::shared_ptr<Connection> connection =
5928 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5929 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005930
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005931 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5932 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005933 ALOGE("Created a new connection, but the token %p is already known", token.get());
5934 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005935
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005936 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5937 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005938
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005939 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005940
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005941 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005942 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005943 }
Garfield Tan15601662020-09-22 15:32:38 -07005944
Michael Wright3dd60e22019-03-27 22:06:44 +00005945 // Wake the looper because some connections have changed.
5946 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005947 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005948}
5949
Garfield Tan15601662020-09-22 15:32:38 -07005950status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005952 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953
Harry Cutts33476232023-01-30 19:57:29 +00005954 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 if (status) {
5956 return status;
5957 }
5958 } // release lock
5959
5960 // Wake the poll loop because removing the connection may have changed the current
5961 // synchronization state.
5962 mLooper->wake();
5963 return OK;
5964}
5965
Garfield Tan15601662020-09-22 15:32:38 -07005966status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5967 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005968 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005969 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005970 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 return BAD_VALUE;
5972 }
5973
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005974 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005975
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005977 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 }
5979
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005980 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981
5982 nsecs_t currentTime = now();
5983 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5984
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005985 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 return OK;
5987}
5988
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005989void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005990 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5991 auto& [displayId, monitors] = *it;
5992 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005993 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005994 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005995
Michael Wright3dd60e22019-03-27 22:06:44 +00005996 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005997 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005998 } else {
5999 ++it;
6000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001 }
6002}
6003
Michael Wright3dd60e22019-03-27 22:06:44 +00006004status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006005 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006006 return pilferPointersLocked(token);
6007}
Michael Wright3dd60e22019-03-27 22:06:44 +00006008
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006009status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006010 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6011 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006012 LOG(WARNING)
6013 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006014 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006015 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006016
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006017 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006018 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006019 LOG(WARNING)
6020 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6021 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006022 return BAD_VALUE;
6023 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006024 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006025 if (deviceIds.empty()) {
6026 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006027 return BAD_VALUE;
6028 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006029
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006030 for (const DeviceId deviceId : deviceIds) {
6031 TouchState& state = *statePtr;
6032 TouchedWindow& window = *windowPtr;
6033 // Send cancel events to all the input channels we're stealing from.
6034 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6035 "input channel stole pointer stream");
6036 options.deviceId = deviceId;
6037 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006038 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6039 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006040 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006041
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006042 std::string canceledWindows;
6043 for (const TouchedWindow& w : state.windows) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006044 const std::shared_ptr<Connection> connection =
6045 getConnectionLocked(w.windowHandle->getToken());
6046 if (connection != nullptr && connection->getToken() != token) {
6047 synthesizeCancelationEventsForConnectionLocked(connection, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006048 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006049 canceledWindows += connection->getInputChannelName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006050 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006051 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006052 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006053 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006054 << " is stealing input gesture for device " << deviceId << " from "
6055 << canceledWindows;
6056
6057 // Prevent the gesture from being sent to any other windows.
6058 // This only blocks relevant pointers to be sent to other windows
6059 window.addPilferingPointers(deviceId, pointerIds);
6060
6061 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006062 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006063 return OK;
6064}
6065
Prabir Pradhan99987712020-11-10 18:43:05 -08006066void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6067 { // acquire lock
6068 std::scoped_lock _l(mLock);
6069 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006070 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006071 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6072 windowHandle != nullptr ? windowHandle->getName().c_str()
6073 : "token without window");
6074 }
6075
Vishnu Nairc519ff72021-01-21 08:23:08 -08006076 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006077 if (focusedToken != windowToken) {
6078 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6079 enabled ? "enable" : "disable");
6080 return;
6081 }
6082
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006083 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006084 ALOGW("Ignoring request to %s Pointer Capture: "
6085 "window has %s requested pointer capture.",
6086 enabled ? "enable" : "disable", enabled ? "already" : "not");
6087 return;
6088 }
6089
Christine Franksb768bb42021-11-29 12:11:31 -08006090 if (enabled) {
6091 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6092 mIneligibleDisplaysForPointerCapture.end(),
6093 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6094 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6095 return;
6096 }
6097 }
6098
Prabir Pradhan99987712020-11-10 18:43:05 -08006099 setPointerCaptureLocked(enabled);
6100 } // release lock
6101
6102 // Wake the thread to process command entries.
6103 mLooper->wake();
6104}
6105
Christine Franksb768bb42021-11-29 12:11:31 -08006106void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6107 { // acquire lock
6108 std::scoped_lock _l(mLock);
6109 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6110 if (!isEligible) {
6111 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6112 }
6113 } // release lock
6114}
6115
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006116std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006117 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006118 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006119 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006120 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006121 }
6122 }
6123 }
6124 return std::nullopt;
6125}
6126
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006127std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6128 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006129 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006130 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006131 }
6132
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006133 for (const auto& [token, connection] : mConnectionsByToken) {
6134 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006135 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 }
6137 }
Robert Carr4e670e52018-08-15 13:26:12 -07006138
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006139 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140}
6141
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006142std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006143 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006144 if (connection == nullptr) {
6145 return "<nullptr>";
6146 }
6147 return connection->getInputChannelName();
6148}
6149
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006150void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006151 mAnrTracker.eraseToken(connection->getToken());
6152 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006153}
6154
Prabir Pradhancef936d2021-07-21 16:17:52 +00006155void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006156 const std::shared_ptr<Connection>& connection,
6157 uint32_t seq, bool handled,
6158 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006159 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006160 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006161
6162 { // Start critical section
6163 auto dispatchEntryIt =
6164 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6165 [seq](auto& e) { return e->seq == seq; });
6166 if (dispatchEntryIt == connection->waitQueue.end()) {
6167 return;
6168 }
6169
6170 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6171
6172 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6173 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006174 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006175 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6176 }
6177 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006178 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006179 dispatchEntry.deliveryTime, consumeTime, finishTime);
6180 }
6181
6182 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6184 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006185 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006186 }
6187 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006188
6189 // Dequeue the event and start the next cycle.
6190 // Because the lock might have been released, it is possible that the
6191 // contents of the wait queue to have been drained, so we need to double-check
6192 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006193 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6194 [seq](auto& e) { return e->seq == seq; });
6195 if (entryIt != connection->waitQueue.end()) {
6196 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6197 connection->waitQueue.erase(entryIt);
6198
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006199 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006200 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6201 if (!connection->responsive) {
6202 connection->responsive = isConnectionResponsive(*connection);
6203 if (connection->responsive) {
6204 // The connection was unresponsive, and now it's responsive.
6205 processConnectionResponsiveLocked(*connection);
6206 }
6207 }
6208 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006209 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006210 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6211 // Only dispatch fallbacks if there is a window for the connection.
6212 if (windowHandle != nullptr) {
6213 const auto inputTarget =
6214 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6215 dispatchEntry->targetFlags,
6216 fallbackKeyEntry->downTime);
6217 if (inputTarget.has_value()) {
6218 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6219 *inputTarget);
6220 }
6221 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006222 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006223 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006224 }
6225
6226 // Start the next dispatch cycle for this connection.
6227 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228}
6229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6231 const sp<IBinder>& newToken) {
6232 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6233 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006234 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006235 };
6236 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237}
6238
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6240 auto command = [this, token, x, y]() REQUIRES(mLock) {
6241 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006242 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 };
6244 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006245}
6246
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006247void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006248 if (connection == nullptr) {
6249 LOG_ALWAYS_FATAL("Caller must check for nullness");
6250 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006251 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6252 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006253 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006254 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006255 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006256 return;
6257 }
6258 /**
6259 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6260 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6261 * has changed. This could cause newer entries to time out before the already dispatched
6262 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6263 * processes the events linearly. So providing information about the oldest entry seems to be
6264 * most useful.
6265 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006266 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6267 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006268 std::string reason =
6269 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006270 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006271 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006272 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006273 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006274 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006275
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006276 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6277
6278 // Stop waking up for events on this connection, it is already unresponsive
6279 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006280}
6281
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006282void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6283 std::string reason =
6284 StringPrintf("%s does not have a focused window", application->getName().c_str());
6285 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006286
Yabin Cui8eb9c552023-06-08 18:05:07 +00006287 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006289 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290 };
6291 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006292}
6293
chaviw98318de2021-05-19 16:45:23 -05006294void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006295 const std::string& reason) {
6296 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6297 updateLastAnrStateLocked(windowLabel, reason);
6298}
6299
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006300void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6301 const std::string& reason) {
6302 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006303 updateLastAnrStateLocked(windowLabel, reason);
6304}
6305
6306void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6307 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006309 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310 struct tm tm;
6311 localtime_r(&t, &tm);
6312 char timestr[64];
6313 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006314 mLastAnrState.clear();
6315 mLastAnrState += INDENT "ANR:\n";
6316 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006317 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6318 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006319 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320}
6321
Prabir Pradhancef936d2021-07-21 16:17:52 +00006322void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006323 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006324 const KeyEvent event = createKeyEvent(entry);
6325 nsecs_t delay = 0;
6326 { // release lock
6327 scoped_unlock unlock(mLock);
6328 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006329 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006330 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6331 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6332 std::to_string(t.duration().count()).c_str());
6333 }
6334 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335
6336 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006337 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006338 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006339 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006340 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006341 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006342 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344}
6345
Prabir Pradhancef936d2021-07-21 16:17:52 +00006346void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006347 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006349 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006350 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006351 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006352 };
6353 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006354}
6355
Prabir Pradhanedd96402022-02-15 01:46:16 -08006356void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006357 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006358 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006359 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006360 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006361 };
6362 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006363}
6364
6365/**
6366 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6367 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6368 * command entry to the command queue.
6369 */
6370void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6371 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006372 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006373 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006374 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006375 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006376 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006377 pid = findMonitorPidByTokenLocked(connectionToken);
6378 } else {
6379 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006380 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006381 reason.c_str());
6382 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6383 if (handle != nullptr) {
6384 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006385 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006386 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006387 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006388}
6389
6390/**
6391 * Tell the policy that a connection has become responsive so that it can stop ANR.
6392 */
6393void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006394 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006395 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006396 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006397 pid = findMonitorPidByTokenLocked(connectionToken);
6398 } else {
6399 // The connection is a window
6400 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6401 if (handle != nullptr) {
6402 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006403 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006404 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006405 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006406}
6407
Prabir Pradhan24047542023-11-02 17:14:59 +00006408std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006409 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006410 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006411 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006412 if (!handled) {
6413 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006414 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006415 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006416 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006418
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006419 // Get the fallback key state.
6420 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006421 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006422 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006423 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006424 connection->inputState.removeFallbackKey(originalKeyCode);
6425 }
6426
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006427 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428 // If the application handles the original key for which we previously
6429 // generated a fallback or if the window is not a foreground window,
6430 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006431 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006432 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6434 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6435 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6436 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6437 keyEntry.policyFlags);
6438 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006439 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006440 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441
6442 mLock.unlock();
6443
Prabir Pradhana41d2442023-04-20 21:30:40 +00006444 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006445 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6446 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006447 unhandledKeyFallback) {
6448 event = *unhandledKeyFallback;
6449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006450
6451 mLock.lock();
6452
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006453 // Cancel the fallback key, but only if we still have a window for the channel.
6454 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006455 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006456 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6457 if (windowHandle != nullptr) {
6458 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6459 "application handled the original non-fallback key "
6460 "or is no longer a foreground target, "
6461 "canceling previously dispatched fallback key");
6462 options.keyCode = *fallbackKeyCode;
6463 synthesizeCancelationEventsForConnectionLocked(connection, options);
6464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006465 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 connection->inputState.removeFallbackKey(originalKeyCode);
6467 }
6468 } else {
6469 // If the application did not handle a non-fallback key, first check
6470 // that we are in a good state to perform unhandled key event processing
6471 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006472 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006473 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006474 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6475 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6476 "since this is not an initial down. "
6477 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6478 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6479 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006480 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006482
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006484 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6485 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6486 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6487 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006489 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490
6491 mLock.unlock();
6492
Prabir Pradhana41d2442023-04-20 21:30:40 +00006493 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006494 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6495 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006496 fb) {
6497 fallback = true;
6498 event = *fb;
6499 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500
6501 mLock.lock();
6502
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006503 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006504 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006505 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006506 }
6507
6508 // Latch the fallback keycode for this key on an initial down.
6509 // The fallback keycode cannot change at any other point in the lifecycle.
6510 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006512 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006514 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006517 }
6518
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006519 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006520
6521 // Cancel the fallback key if the policy decides not to send it anymore.
6522 // We will continue to dispatch the key to the policy but we will no
6523 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006524 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6525 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006526 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6527 if (fallback) {
6528 ALOGD("Unhandled key event: Policy requested to send key %d"
6529 "as a fallback for %d, but on the DOWN it had requested "
6530 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006531 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006532 } else {
6533 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6534 "but on the DOWN it had requested to send %d. "
6535 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006536 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006537 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006539
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006540 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6541 if (windowHandle != nullptr) {
6542 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6543 "canceling fallback, policy no longer desires it");
6544 options.keyCode = *fallbackKeyCode;
6545 synthesizeCancelationEventsForConnectionLocked(connection, options);
6546 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547
6548 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006549 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006550 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006551 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006552 }
6553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006555 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6556 {
6557 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006558 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006559 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006560 for (const auto& [key, value] : fallbackKeys) {
6561 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006562 }
6563 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6564 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006566 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006567
6568 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006569 // Return the fallback key that we want dispatched to the channel.
6570 std::unique_ptr<KeyEntry> newEntry =
6571 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6572 event.getEventTime(), event.getDeviceId(),
6573 event.getSource(), event.getDisplayId(),
6574 keyEntry.policyFlags, keyEntry.action,
6575 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6576 *fallbackKeyCode, event.getScanCode(),
6577 event.getMetaState(), event.getRepeatCount(),
6578 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006579 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6580 ALOGD("Unhandled key event: Dispatching fallback key. "
6581 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006582 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006583 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006584 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006585 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006586 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6587 ALOGD("Unhandled key event: No fallback key.");
6588 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006589
6590 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006591 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 }
6593 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006594 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595}
6596
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597void InputDispatcher::traceInboundQueueLengthLocked() {
6598 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006599 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600 }
6601}
6602
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006603void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 if (ATRACE_ENABLED()) {
6605 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006606 snprintf(counterName, sizeof(counterName), "oq:%s",
6607 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006608 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 }
6610}
6611
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006612void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613 if (ATRACE_ENABLED()) {
6614 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006615 snprintf(counterName, sizeof(counterName), "wq:%s",
6616 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006617 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618 }
6619}
6620
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006621void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006622 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006624 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625 dumpDispatchStateLocked(dump);
6626
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006627 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006628 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006629 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 }
6631}
6632
6633void InputDispatcher::monitor() {
6634 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006635 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006636 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006637 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006638}
6639
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006640/**
6641 * Wake up the dispatcher and wait until it processes all events and commands.
6642 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6643 * this method can be safely called from any thread, as long as you've ensured that
6644 * the work you are interested in completing has already been queued.
6645 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006646bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006647 /**
6648 * Timeout should represent the longest possible time that a device might spend processing
6649 * events and commands.
6650 */
6651 constexpr std::chrono::duration TIMEOUT = 100ms;
6652 std::unique_lock lock(mLock);
6653 mLooper->wake();
6654 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6655 return result == std::cv_status::no_timeout;
6656}
6657
Vishnu Naire798b472020-07-23 13:52:21 -07006658/**
6659 * Sets focus to the window identified by the token. This must be called
6660 * after updating any input window handles.
6661 *
6662 * Params:
6663 * request.token - input channel token used to identify the window that should gain focus.
6664 * request.focusedToken - the token that the caller expects currently to be focused. If the
6665 * specified token does not match the currently focused window, this request will be dropped.
6666 * If the specified focused token matches the currently focused window, the call will succeed.
6667 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6668 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6669 * when requesting the focus change. This determines which request gets
6670 * precedence if there is a focus change request from another source such as pointer down.
6671 */
Vishnu Nair958da932020-08-21 17:12:37 -07006672void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6673 { // acquire lock
6674 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006675 std::optional<FocusResolver::FocusChanges> changes =
6676 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6677 if (changes) {
6678 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006679 }
6680 } // release lock
6681 // Wake up poll loop since it may need to make new input dispatching choices.
6682 mLooper->wake();
6683}
6684
Vishnu Nairc519ff72021-01-21 08:23:08 -08006685void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6686 if (changes.oldFocus) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006687 std::shared_ptr<Connection> focusedConnection = getConnectionLocked(changes.oldFocus);
6688 if (focusedConnection) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006689 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006690 "focus left window");
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006691 synthesizeCancelationEventsForConnectionLocked(focusedConnection, options);
Harry Cutts33476232023-01-30 19:57:29 +00006692 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006693 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006694 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006695 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006696 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006697 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006698 }
6699
Prabir Pradhan99987712020-11-10 18:43:05 -08006700 // If a window has pointer capture, then it must have focus. We need to ensure that this
6701 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6702 // If the window loses focus before it loses pointer capture, then the window can be in a state
6703 // where it has pointer capture but not focus, violating the contract. Therefore we must
6704 // dispatch the pointer capture event before the focus event. Since focus events are added to
6705 // the front of the queue (above), we add the pointer capture event to the front of the queue
6706 // after the focus events are added. This ensures the pointer capture event ends up at the
6707 // front.
6708 disablePointerCaptureForcedLocked();
6709
Vishnu Nairc519ff72021-01-21 08:23:08 -08006710 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006711 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006712 }
6713}
Vishnu Nair958da932020-08-21 17:12:37 -07006714
Prabir Pradhan99987712020-11-10 18:43:05 -08006715void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006716 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006717 return;
6718 }
6719
6720 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6721
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006722 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006723 setPointerCaptureLocked(false);
6724 }
6725
6726 if (!mWindowTokenWithPointerCapture) {
6727 // No need to send capture changes because no window has capture.
6728 return;
6729 }
6730
6731 if (mPendingEvent != nullptr) {
6732 // Move the pending event to the front of the queue. This will give the chance
6733 // for the pending event to be dropped if it is a captured event.
6734 mInboundQueue.push_front(mPendingEvent);
6735 mPendingEvent = nullptr;
6736 }
6737
6738 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006739 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006740 mInboundQueue.push_front(std::move(entry));
6741}
6742
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006743void InputDispatcher::setPointerCaptureLocked(bool enable) {
6744 mCurrentPointerCaptureRequest.enable = enable;
6745 mCurrentPointerCaptureRequest.seq++;
6746 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006747 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006748 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006749 };
6750 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006751}
6752
Vishnu Nair599f1412021-06-21 10:39:58 -07006753void InputDispatcher::displayRemoved(int32_t displayId) {
6754 { // acquire lock
6755 std::scoped_lock _l(mLock);
6756 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006757 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006758 setFocusedApplicationLocked(displayId, nullptr);
6759 // Call focus resolver to clean up stale requests. This must be called after input windows
6760 // have been removed for the removed display.
6761 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006762 // Reset pointer capture eligibility, regardless of previous state.
6763 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006764 // Remove the associated touch mode state.
6765 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006766 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006767 } // release lock
6768
6769 // Wake up poll loop since it may need to make new input dispatching choices.
6770 mLooper->wake();
6771}
6772
Patrick Williamsd828f302023-04-28 17:52:08 -05006773void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006774 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6775 {
6776 // acquire lock
6777 std::scoped_lock _l(mLock);
6778 logDispatchStateLocked();
6779 }
6780 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6781 result.error().message().c_str());
6782 };
chaviw15fab6f2021-06-07 14:15:52 -05006783 // The listener sends the windows as a flattened array. Separate the windows by display for
6784 // more convenient parsing.
6785 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006786 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006787 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006788 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006789 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006790
6791 { // acquire lock
6792 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006793
6794 // Ensure that we have an entry created for all existing displays so that if a displayId has
6795 // no windows, we can tell that the windows were removed from the display.
6796 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6797 handlesPerDisplay[displayId];
6798 }
6799
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006800 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006801 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006802 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6803 }
6804
6805 for (const auto& [displayId, handles] : handlesPerDisplay) {
6806 setInputWindowsLocked(handles, displayId);
6807 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006808
6809 if (update.vsyncId < mWindowInfosVsyncId) {
6810 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6811 ", current update vsync id: %" PRId64,
6812 mWindowInfosVsyncId, update.vsyncId);
6813 }
6814 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006815 }
6816 // Wake up poll loop since it may need to make new input dispatching choices.
6817 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006818}
6819
Vishnu Nair062a8672021-09-03 16:07:44 -07006820bool InputDispatcher::shouldDropInput(
6821 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006822 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6823 (windowHandle->getInfo()->inputConfig.test(
6824 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006825 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006826 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6827 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006828 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006829 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006830 windowHandle->getInfo()->displayId);
6831 return true;
6832 }
6833 return false;
6834}
6835
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006836void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006837 const gui::WindowInfosUpdate& update) {
6838 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006839}
6840
Arthur Hungdfd528e2021-12-08 13:23:04 +00006841void InputDispatcher::cancelCurrentTouch() {
6842 {
6843 std::scoped_lock _l(mLock);
6844 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006845 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006846 "cancel current touch");
6847 synthesizeCancelationEventsForAllConnectionsLocked(options);
6848
6849 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006850 }
6851 // Wake up poll loop since there might be work to do.
6852 mLooper->wake();
6853}
6854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006855void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6856 std::scoped_lock _l(mLock);
6857 mMonitorDispatchingTimeout = timeout;
6858}
6859
Arthur Hungc539dbb2022-12-08 07:45:36 +00006860void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6861 const sp<WindowInfoHandle>& oldWindowHandle,
6862 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006863 TouchState& state, int32_t deviceId,
6864 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006865 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006866 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006867 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6868 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6869 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6870 newWindowHandle->getInfo()->inputConfig.test(
6871 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6872 const sp<WindowInfoHandle> oldWallpaper =
6873 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6874 const sp<WindowInfoHandle> newWallpaper =
6875 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6876 if (oldWallpaper == newWallpaper) {
6877 return;
6878 }
6879
6880 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006881 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006882 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006883 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006884 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006885 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006886 }
6887
6888 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006889 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6890 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006891 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006892 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006893 }
6894}
6895
6896void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6897 ftl::Flags<InputTarget::Flags> newTargetFlags,
6898 const sp<WindowInfoHandle> fromWindowHandle,
6899 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006900 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006901 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006902 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6903 fromWindowHandle->getInfo()->inputConfig.test(
6904 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6905 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6906 toWindowHandle->getInfo()->inputConfig.test(
6907 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6908
6909 const sp<WindowInfoHandle> oldWallpaper =
6910 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6911 const sp<WindowInfoHandle> newWallpaper =
6912 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6913 if (oldWallpaper == newWallpaper) {
6914 return;
6915 }
6916
6917 if (oldWallpaper != nullptr) {
6918 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6919 "transferring touch focus to another window");
6920 state.removeWindowByToken(oldWallpaper->getToken());
6921 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6922 }
6923
6924 if (newWallpaper != nullptr) {
6925 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006926 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006927 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6928 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006929 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006930 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006931 std::shared_ptr<Connection> wallpaperConnection =
6932 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006933 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006934 std::shared_ptr<Connection> toConnection =
6935 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006936 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6937 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6938 wallpaperFlags);
6939 }
6940 }
6941}
6942
6943sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6944 const sp<WindowInfoHandle>& windowHandle) const {
6945 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6946 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6947 bool foundWindow = false;
6948 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6949 if (!foundWindow && otherHandle != windowHandle) {
6950 continue;
6951 }
6952 if (windowHandle == otherHandle) {
6953 foundWindow = true;
6954 continue;
6955 }
6956
6957 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6958 return otherHandle;
6959 }
6960 }
6961 return nullptr;
6962}
6963
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006964void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6965 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006966 std::scoped_lock _l(mLock);
6967
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006968 mConfig.keyRepeatTimeout = timeout.count();
6969 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006970}
6971
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006972bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6973 DeviceId deviceId, int32_t pointerId) {
6974 std::scoped_lock _l(mLock);
6975 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6976 if (touchStateIt == mTouchStatesByDisplay.end()) {
6977 return false;
6978 }
6979 for (const TouchedWindow& window : touchStateIt->second.windows) {
6980 if (window.windowHandle->getToken() == token &&
6981 (window.hasTouchingPointer(deviceId, pointerId) ||
6982 window.hasHoveringPointer(deviceId, pointerId))) {
6983 return true;
6984 }
6985 }
6986 return false;
6987}
6988
Garfield Tane84e6f92019-08-29 17:28:41 -07006989} // namespace android::inputdispatcher