blob: f31884e25013a766b08b78e4e3c46c42b2c8e135 [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 Pradhanc88b1fa2024-01-23 21:48:03 +0000368std::unique_ptr<DispatchEntry> createDispatchEntry(const IdGenerator& idGenerator,
369 const InputTarget& inputTarget,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000370 std::shared_ptr<const EventEntry> eventEntry,
371 ftl::Flags<InputTarget::Flags> inputTargetFlags,
372 int64_t vsyncId) {
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000373 const bool zeroCoords = inputTargetFlags.test(InputTarget::Flags::ZERO_COORDS);
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000374 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
375 const std::optional<int32_t> windowId =
376 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
377 // Assume the only targets that are not associated with a window are global monitors, and use
378 // the system UID for global monitors for tracing purposes.
379 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000380
381 if (inputTarget.useDefaultPointerTransform() && !zeroCoords) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700383 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700384 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000385 inputTarget.globalScaleFactor, uid, vsyncId,
386 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387 }
388
389 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
390 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
391
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000392 std::vector<PointerCoords> pointerCoords{motionEntry.getPointerCount()};
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000393
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000394 const ui::Transform* transform = &kIdentityTransform;
395 const ui::Transform* displayTransform = &kIdentityTransform;
396 if (zeroCoords) {
397 std::for_each(pointerCoords.begin(), pointerCoords.end(), [](auto& pc) { pc.clear(); });
398 } else {
399 // Use the first pointer information to normalize all other pointers. This could be any
400 // pointer as long as all other pointers are normalized to the same value and the final
401 // DispatchEntry uses the transform for the normalized pointer.
402 transform =
403 &inputTarget.getTransformForPointer(firstMarkedBit(inputTarget.getPointerIds()));
404 const ui::Transform inverseTransform = transform->inverse();
405 displayTransform = &inputTarget.displayTransform;
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000406
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000407 // Iterate through all pointers in the event to normalize against the first.
408 for (size_t i = 0; i < motionEntry.getPointerCount(); i++) {
409 PointerCoords& newCoords = pointerCoords[i];
410 const auto pointerId = motionEntry.pointerProperties[i].id;
411 const ui::Transform& currTransform = inputTarget.getTransformForPointer(pointerId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000413 newCoords.copyFrom(motionEntry.pointerCoords[i]);
414 // First, apply the current pointer's transform to update the coordinates into
415 // window space.
416 newCoords.transform(currTransform);
417 // Next, apply the inverse transform of the normalized coordinates so the
418 // current coordinates are transformed into the normalized coordinate space.
419 newCoords.transform(inverseTransform);
420 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000421 }
422
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700423 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000424 std::make_unique<MotionEntry>(idGenerator.nextId(), motionEntry.injectionState,
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000425 motionEntry.eventTime, motionEntry.deviceId,
426 motionEntry.source, motionEntry.displayId,
427 motionEntry.policyFlags, motionEntry.action,
428 motionEntry.actionButton, motionEntry.flags,
429 motionEntry.metaState, motionEntry.buttonState,
430 motionEntry.classification, motionEntry.edgeFlags,
431 motionEntry.xPrecision, motionEntry.yPrecision,
432 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
433 motionEntry.downTime, motionEntry.pointerProperties,
434 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000435
436 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700437 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +0000438 *transform, *displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000439 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000440 return dispatchEntry;
441}
442
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500443template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500445 if (lhs == nullptr && rhs == nullptr) {
446 return true;
447 }
448 if (lhs == nullptr || rhs == nullptr) {
449 return false;
450 }
451 return *lhs == *rhs;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000455 KeyEvent event;
456 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
457 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
458 entry.repeatCount, entry.downTime, entry.eventTime);
459 return event;
460}
461
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000462bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000463 // Do not keep track of gesture monitors. They receive every event and would disproportionately
464 // affect the statistics.
465 if (connection.monitor) {
466 return false;
467 }
468 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
469 if (!connection.responsive) {
470 return false;
471 }
472 return true;
473}
474
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000475bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000476 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
477 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000478 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
479 return false;
480 }
481 // Only track latency for events that originated from hardware
482 if (eventEntry.isSynthesized()) {
483 return false;
484 }
485 const EventEntry::Type& inputEventEntryType = eventEntry.type;
486 if (inputEventEntryType == EventEntry::Type::KEY) {
487 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
488 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
489 return false;
490 }
491 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
492 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
493 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
494 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
495 return false;
496 }
497 } else {
498 // Not a key or a motion
499 return false;
500 }
501 if (!shouldReportMetricsForConnection(connection)) {
502 return false;
503 }
504 return true;
505}
506
Prabir Pradhancef936d2021-07-21 16:17:52 +0000507/**
508 * Connection is responsive if it has no events in the waitQueue that are older than the
509 * current time.
510 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000511bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000512 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000513 for (const auto& dispatchEntry : connection.waitQueue) {
514 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000515 return false;
516 }
517 }
518 return true;
519}
520
Antonio Kantekf16f2832021-09-28 04:39:20 +0000521// Returns true if the event type passed as argument represents a user activity.
522bool isUserActivityEvent(const EventEntry& eventEntry) {
523 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000524 case EventEntry::Type::CONFIGURATION_CHANGED:
525 case EventEntry::Type::DEVICE_RESET:
526 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000527 case EventEntry::Type::FOCUS:
528 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000529 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000530 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000531 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000532 case EventEntry::Type::KEY:
533 case EventEntry::Type::MOTION:
534 return true;
535 }
536}
537
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800538// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000539bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000540 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800541 const auto inputConfig = windowInfo.inputConfig;
542 if (windowInfo.displayId != displayId ||
543 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800544 return false;
545 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700546 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800547 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548 return false;
549 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000550
551 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
552 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
553 // the window. Points on the right and bottom edges should not be inside the window, so we need
554 // to be careful about performing a hit test when the display is rotated, since the "right" and
555 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
556 // logical display in which WM determined the bounds. Perform the hit test in the logical
557 // display space to ensure these edges are considered correctly in all orientations.
558 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
559 const auto p = displayTransform.transform(x, y);
560 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800561 return false;
562 }
563 return true;
564}
565
Prabir Pradhand65552b2021-10-07 11:23:50 -0700566bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
567 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000568 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700569}
570
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800571// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000572// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
573// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
574// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800575// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000576bool canReceiveForegroundTouches(const WindowInfo& info) {
577 // A non-touchable window can still receive touch events (e.g. in the case of
578 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
579 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
580}
581
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000582bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700583 if (windowHandle == nullptr) {
584 return false;
585 }
586 const WindowInfo* windowInfo = windowHandle->getInfo();
587 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
588 return true;
589 }
590 return false;
591}
592
Prabir Pradhan5735a322022-04-11 17:23:34 +0000593// Checks targeted injection using the window's owner's uid.
594// Returns an empty string if an entry can be sent to the given window, or an error message if the
595// entry is a targeted injection whose uid target doesn't match the window owner.
596std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
597 const EventEntry& entry) {
598 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
599 // The event was not injected, or the injected event does not target a window.
600 return {};
601 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000602 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000603 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000604 return StringPrintf("No valid window target for injection into uid %s.",
605 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000606 }
607 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000608 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
609 "owned by uid %s.",
610 uid.toString().c_str(), window->getName().c_str(),
611 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000612 }
613 return {};
614}
615
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000616std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700617 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
618 // Always dispatch mouse events to cursor position.
619 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000620 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700621 }
622
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700623 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000624 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
625 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700626}
627
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700628std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
629 if (eventEntry.type == EventEntry::Type::KEY) {
630 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
631 return keyEntry.downTime;
632 } else if (eventEntry.type == EventEntry::Type::MOTION) {
633 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
634 return motionEntry.downTime;
635 }
636 return std::nullopt;
637}
638
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000639/**
640 * Compare the old touch state to the new touch state, and generate the corresponding touched
641 * windows (== input targets).
642 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
643 * If the pointer just entered the new window, produce HOVER_ENTER.
644 * For pointers remaining in the window, produce HOVER_MOVE.
645 */
646std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
647 const TouchState& newTouchState,
648 const MotionEntry& entry) {
649 std::vector<TouchedWindow> out;
650 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700651
652 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
653 // ACTION_SCROLL events should not affect the hovering pointer dispatch
654 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000655 }
656
657 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800658 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000659
660 std::set<sp<WindowInfoHandle>> oldWindows;
661 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800662 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000663 }
664
665 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800666 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000667
668 // If the pointer is no longer in the new window set, send HOVER_EXIT.
669 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
670 if (newWindows.find(oldWindow) == newWindows.end()) {
671 TouchedWindow touchedWindow;
672 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000673 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000674 out.push_back(touchedWindow);
675 }
676 }
677
678 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
679 TouchedWindow touchedWindow;
680 touchedWindow.windowHandle = newWindow;
681 if (oldWindows.find(newWindow) == oldWindows.end()) {
682 // Any windows that have this pointer now, and didn't have it before, should get
683 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000684 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 } else {
686 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700687 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700688 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000689 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
690 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700691 // The Accessibility injected touch exploration event stream
692 // has known inconsistencies, so log ERROR instead of
693 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700694 severity = android::base::LogSeverity::ERROR;
695 }
696 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700697 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000698 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000699 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800700 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000701 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
702 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
703 }
704 out.push_back(touchedWindow);
705 }
706 return out;
707}
708
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800709template <typename T>
710std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
711 left.insert(left.end(), right.begin(), right.end());
712 return left;
713}
714
Harry Cuttsb166c002023-05-09 13:06:05 +0000715// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
716// both.
717void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
718 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
719 if (!window.windowHandle->getInfo()->inputConfig.test(
720 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
721 // In addition to TouchState, erase this window from the input targets! We don't have a
722 // good way to do this today except by adding a nested loop.
723 // TODO(b/282025641): simplify this code once InputTargets are being identified
724 // separately from TouchedWindows.
725 std::erase_if(targets, [&](const InputTarget& target) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800726 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000727 });
728 return true;
729 }
730 return false;
731 });
732}
733
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700734/**
735 * In general, touch should be always split between windows. Some exceptions:
736 * 1. Don't split touch if all of the below is true:
737 * (a) we have an active pointer down *and*
738 * (b) a new pointer is going down that's from the same device *and*
739 * (c) the window that's receiving the current pointer does not support split touch.
740 * 2. Don't split mouse events
741 */
742bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
743 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
744 // We should never split mouse events
745 return false;
746 }
747 for (const TouchedWindow& touchedWindow : touchState.windows) {
748 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
749 // Spy windows should not affect whether or not touch is split.
750 continue;
751 }
752 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
753 continue;
754 }
755 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
756 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
757 // Wallpaper window should not affect whether or not touch is split
758 continue;
759 }
760
761 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
762 return false;
763 }
764 }
765 return true;
766}
767
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700768/**
769 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
770 */
771bool isStylusActiveInDisplay(
772 int32_t displayId,
773 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
774 const auto it = touchStatesByDisplay.find(displayId);
775 if (it == touchStatesByDisplay.end()) {
776 return false;
777 }
778 const TouchState& state = it->second;
779 return state.hasActiveStylus();
780}
781
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800782Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
783 struct HashFunction {
784 size_t operator()(const WindowInfo& info) const { return info.id; }
785 };
786
787 std::unordered_set<WindowInfo, HashFunction> windowSet;
788 for (const WindowInfo& info : update.windowInfos) {
789 const auto [_, inserted] = windowSet.insert(info);
790 if (!inserted) {
791 return Error() << "Duplicate entry for " << info;
792 }
793 }
794 return {};
795}
796
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800797int32_t getUserActivityEventType(const EventEntry& eventEntry) {
798 switch (eventEntry.type) {
799 case EventEntry::Type::KEY: {
800 return USER_ACTIVITY_EVENT_BUTTON;
801 }
802 case EventEntry::Type::MOTION: {
803 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
804 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
805 return USER_ACTIVITY_EVENT_TOUCH;
806 }
807 return USER_ACTIVITY_EVENT_OTHER;
808 }
809 default: {
810 LOG_ALWAYS_FATAL("%s events are not user activity",
811 ftl::enum_string(eventEntry.type).c_str());
812 }
813 }
814}
815
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +0000816std::pair<bool /*cancelPointers*/, bool /*cancelNonPointers*/> expandCancellationMode(
817 CancelationOptions::Mode mode) {
818 switch (mode) {
819 case CancelationOptions::Mode::CANCEL_ALL_EVENTS:
820 return {true, true};
821 case CancelationOptions::Mode::CANCEL_POINTER_EVENTS:
822 return {true, false};
823 case CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS:
824 return {false, true};
825 case CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS:
826 return {false, true};
827 }
828}
829
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000830} // namespace
831
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832// --- InputDispatcher ---
833
Prabir Pradhana41d2442023-04-20 21:30:40 +0000834InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000835 : InputDispatcher(policy,
836 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
837 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000838
839InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
840 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700841 : mPolicy(policy),
842 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700843 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800844 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800845 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700846 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800847 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700848 mDispatchEnabled(false),
849 mDispatchFrozen(false),
850 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100851 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000852 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800853 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000854 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000855 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700856 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800857 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700859 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700860#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700861 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700862#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700863 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000864
865 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000866 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000867 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800868
869 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870}
871
872InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
Prabir Pradhancef936d2021-07-21 16:17:52 +0000875 resetKeyRepeatLocked();
876 releasePendingEventLocked();
877 drainInboundQueueLocked();
878 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000880 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700881 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800882 removeInputChannelLocked(connection->getToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 }
884}
885
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700886status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700887 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700888 return ALREADY_EXISTS;
889 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700890 mThread = std::make_unique<InputThread>(
891 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
892 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700893}
894
895status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700896 if (mThread && mThread->isCallingThread()) {
897 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700898 return INVALID_OPERATION;
899 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700900 mThread.reset();
901 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700902}
903
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700905 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800907 std::scoped_lock _l(mLock);
908 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909
910 // Run a dispatch loop if there are no pending commands.
911 // The dispatch loop might enqueue commands to run afterwards.
912 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800913 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
915
916 // Run all pending commands if there are any.
917 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000918 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700919 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800921
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700922 // If we are still waiting for ack on some events,
923 // we might have to wake up earlier to check if an app is anr'ing.
924 const nsecs_t nextAnrCheck = processAnrsLocked();
925 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
926
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800927 // We are about to enter an infinitely long sleep, because we have no commands or
928 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700929 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800930 mDispatcherEnteredIdle.notify_all();
931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 } // release lock
933
934 // Wait for callback or timeout or wake. (make sure we round up, not down)
935 nsecs_t currentTime = now();
936 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
937 mLooper->pollOnce(timeoutMillis);
938}
939
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700940/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500941 * Raise ANR if there is no focused window.
942 * Before the ANR is raised, do a final state check:
943 * 1. The currently focused application must be the same one we are waiting for.
944 * 2. Ensure we still don't have a focused window.
945 */
946void InputDispatcher::processNoFocusedWindowAnrLocked() {
947 // Check if the application that we are waiting for is still focused.
948 std::shared_ptr<InputApplicationHandle> focusedApplication =
949 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
950 if (focusedApplication == nullptr ||
951 focusedApplication->getApplicationToken() !=
952 mAwaitedFocusedApplication->getApplicationToken()) {
953 // Unexpected because we should have reset the ANR timer when focused application changed
954 ALOGE("Waited for a focused window, but focused application has already changed to %s",
955 focusedApplication->getName().c_str());
956 return; // The focused application has changed.
957 }
958
chaviw98318de2021-05-19 16:45:23 -0500959 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500960 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
961 if (focusedWindowHandle != nullptr) {
962 return; // We now have a focused window. No need for ANR.
963 }
964 onAnrLocked(mAwaitedFocusedApplication);
965}
966
967/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968 * Check if any of the connections' wait queues have events that are too old.
969 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
970 * Return the time at which we should wake up next.
971 */
972nsecs_t InputDispatcher::processAnrsLocked() {
973 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700974 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
976 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
977 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500978 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700979 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500980 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700981 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700982 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500983 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700984 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
985 }
986 }
987
988 // Check if any connection ANRs are due
989 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
990 if (currentTime < nextAnrCheck) { // most likely scenario
991 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
992 }
993
994 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700995 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 if (connection == nullptr) {
997 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
998 return nextAnrCheck;
999 }
1000 connection->responsive = false;
1001 // Stop waking up for this unresponsive connection
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001002 mAnrTracker.eraseToken(connection->getToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00001003 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -07001004 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001005}
1006
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001007std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001008 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001009 if (connection->monitor) {
1010 return mMonitorDispatchingTimeout;
1011 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001012 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001013 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001014 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001015 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001016 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001017}
1018
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001019void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 nsecs_t currentTime = now();
1021
Jeff Browndc5992e2014-04-11 01:27:26 -07001022 // Reset the key repeat timer whenever normal dispatch is suspended while the
1023 // device is in a non-interactive state. This is to ensure that we abort a key
1024 // repeat if the device is just coming out of sleep.
1025 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 resetKeyRepeatLocked();
1027 }
1028
1029 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1030 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001031 if (DEBUG_FOCUS) {
1032 ALOGD("Dispatch frozen. Waiting some more.");
1033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 return;
1035 }
1036
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 // Ready to start a new event.
1038 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001040 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 // Synthesize a key repeat if appropriate.
1042 if (mKeyRepeatState.lastKeyEntry) {
1043 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1044 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1045 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001046 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 }
1049
1050 // Nothing to do if there is no pending event.
1051 if (!mPendingEvent) {
1052 return;
1053 }
1054 } else {
1055 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001056 mPendingEvent = mInboundQueue.front();
1057 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 traceInboundQueueLengthLocked();
1059 }
1060
1061 // Poke user activity for this event.
1062 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001063 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066
1067 // Now we have an event to dispatch.
1068 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001069 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001071 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077
1078 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001079 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081
1082 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001083 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 const ConfigurationChangedEntry& typedEntry =
1085 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 break;
1089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001091 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 const DeviceResetEntry& typedEntry =
1093 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 break;
1097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001099 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001100 std::shared_ptr<const FocusEntry> typedEntry =
1101 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001102 dispatchFocusLocked(currentTime, typedEntry);
1103 done = true;
1104 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1105 break;
1106 }
1107
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001108 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001109 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001110 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1111 done = true;
1112 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1113 break;
1114 }
1115
Prabir Pradhan99987712020-11-10 18:43:05 -08001116 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1117 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001118 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001119 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1120 done = true;
1121 break;
1122 }
1123
arthurhungb89ccb02020-12-30 16:19:01 +08001124 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001125 std::shared_ptr<const DragEntry> typedEntry =
1126 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001127 dispatchDragLocked(currentTime, typedEntry);
1128 done = true;
1129 break;
1130 }
1131
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const KeyEntry> keyEntry =
1134 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001135 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001136 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001138 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1139 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001141 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001142 if (done && mTracer) {
1143 ensureEventTraced(*keyEntry);
1144 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1145 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 break;
1147 }
1148
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001149 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001150 std::shared_ptr<const MotionEntry> motionEntry =
1151 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001153 // The event is stale. However, only drop stale events if there isn't an ongoing
1154 // gesture. That would allow us to complete the processing of the current stroke.
1155 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1156 if (touchStateIt != mTouchStatesByDisplay.end()) {
1157 const TouchState& touchState = touchStateIt->second;
1158 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1159 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1160 dropReason = DropReason::STALE;
1161 }
1162 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001164 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001165 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1166 // Only drop events that are focus-dispatched.
1167 dropReason = DropReason::BLOCKED;
1168 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001170 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001171 if (done && mTracer) {
1172 ensureEventTraced(*motionEntry);
1173 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1174 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
Chris Yef59a2f42020-10-16 12:55:26 -07001177
1178 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001179 std::shared_ptr<const SensorEntry> sensorEntry =
1180 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001181
Chris Yef59a2f42020-10-16 12:55:26 -07001182 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1183 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1184 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1185 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1186 dropReason = DropReason::STALE;
1187 }
1188 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1189 done = true;
1190 break;
1191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 }
1193
1194 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001195 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 }
Michael Wright3a981722015-06-10 15:26:13 +01001198 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199
1200 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001201 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203}
1204
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001205bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001206 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001207}
1208
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001209/**
1210 * Return true if the events preceding this incoming motion event should be dropped
1211 * Return false otherwise (the default behaviour)
1212 */
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001213bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001214 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001215 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001216
1217 // Optimize case where the current application is unresponsive and the user
1218 // decides to touch a window in a different application.
1219 // If the application takes too long to catch up then we drop all events preceding
1220 // the touch into the other window.
1221 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001222 const int32_t displayId = motionEntry.displayId;
1223 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001224 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001225
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001226 sp<WindowInfoHandle> touchedWindowHandle =
1227 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001228 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001229 touchedWindowHandle->getApplicationToken() !=
1230 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001231 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001232 ALOGI("Pruning input queue because user touched a different application while waiting "
1233 "for %s",
1234 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235 return true;
1236 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001237
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001238 // Alternatively, maybe there's a spy window that could handle this event.
1239 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1240 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1241 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001242 const std::shared_ptr<Connection> connection =
1243 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001244 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001245 // This spy window could take more input. Drop all events preceding this
1246 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001247 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001248 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001249 mAwaitedFocusedApplication->getName().c_str());
1250 return true;
1251 }
1252 }
1253 }
1254
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 return false;
1256}
1257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001259 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001261 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 traceInboundQueueLengthLocked();
1263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001265 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001266 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1267 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001270 if (mTracer) {
1271 ensureEventTraced(keyEntry);
1272 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001273
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001274 // If a new up event comes in, and the pending event with same key code has been asked
1275 // to try again later because of the policy. We have to reset the intercept key wake up
1276 // time for it may have been handled in the policy and could be dropped.
1277 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1278 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001279 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001280 if (pendingKey.keyCode == keyEntry.keyCode &&
1281 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001282 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1283 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001284 pendingKey.interceptKeyWakeupTime = 0;
1285 needWake = true;
1286 }
1287 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001288 break;
1289 }
1290
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001291 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001292 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1293 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001294 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1295 if (mTracer) {
1296 ensureEventTraced(motionEntry);
1297 }
1298 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001300 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 }
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001302
1303 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
1304 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
1305 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1306 // Prevent waiting too long for unprocessed events: if we have a pending key event,
1307 // and some other events have not yet been processed, the dispatcher will wait for
1308 // these events to be processed before dispatching the key event. This is because
1309 // the unprocessed events may cause the focus to change (for example, by launching a
1310 // new window or tapping a different window). To prevent waiting too long, we force
1311 // the key to be sent to the currently focused window when a new tap comes in.
1312 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1313 "just send the pending key event to the currently focused window.");
1314 mKeyIsWaitingForEventsTimeout = now();
Linnan Li563916a2024-02-23 16:08:33 +00001315 needWake = true;
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08001316 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001319 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001320 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1321 break;
1322 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001323 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001324 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001325 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001326 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001327 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1328 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001329 // nothing to do
1330 break;
1331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333
1334 return needWake;
1335}
1336
Prabir Pradhan24047542023-11-02 17:14:59 +00001337void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001338 // Do not store sensor event in recent queue to avoid flooding the queue.
1339 if (entry->type != EventEntry::Type::SENSOR) {
1340 mRecentQueue.push_back(entry);
1341 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001342 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001343 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
1345}
1346
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001347sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1348 bool isStylus,
1349 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001351 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001352 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001353 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001354 continue;
1355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001357 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001358 if (!info.isSpy() &&
1359 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001360 return windowHandle;
1361 }
1362 }
1363 return nullptr;
1364}
1365
1366std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001367 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 if (touchedWindow == nullptr) {
1369 return {};
1370 }
1371 // Traverse windows from front to back until we encounter the touched window.
1372 std::vector<InputTarget> outsideTargets;
1373 const auto& windowHandles = getWindowHandlesLocked(displayId);
1374 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1375 if (windowHandle == touchedWindow) {
1376 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1377 // below the touched window will not get ACTION_OUTSIDE event.
1378 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001379 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001380
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001381 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001382 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001383 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1384 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001385 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1386 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001387 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
1389 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001390 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Prabir Pradhand65552b2021-10-07 11:23:50 -07001393std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001394 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001395 // Traverse windows from front to back and gather the touched spy windows.
1396 std::vector<sp<WindowInfoHandle>> spyWindows;
1397 const auto& windowHandles = getWindowHandlesLocked(displayId);
1398 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1399 const WindowInfo& info = *windowHandle->getInfo();
1400
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001401 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001402 continue;
1403 }
1404 if (!info.isSpy()) {
1405 // The first touched non-spy window was found, so return the spy windows touched so far.
1406 return spyWindows;
1407 }
1408 spyWindows.push_back(windowHandle);
1409 }
1410 return spyWindows;
1411}
1412
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 const char* reason;
1415 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001416 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001417 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001418 ALOGD("Dropped event because policy consumed it.");
1419 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 reason = "inbound event was dropped because the policy consumed it";
1421 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001422 case DropReason::DISABLED:
1423 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001424 ALOGI("Dropped event because input dispatch is disabled.");
1425 }
1426 reason = "inbound event was dropped because input dispatch is disabled";
1427 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001428 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001429 LOG(INFO) << "Dropping because the current application is not responding and the user "
1430 "has started interacting with a different application: "
1431 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 reason = "inbound event was dropped because the current application is not responding "
1433 "and the user has started interacting with a different application";
1434 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001435 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 ALOGI("Dropped event because it is stale.");
1437 reason = "inbound event was dropped because it is stale";
1438 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001439 case DropReason::NO_POINTER_CAPTURE:
1440 ALOGI("Dropped event because there is no window with Pointer Capture.");
1441 reason = "inbound event was dropped because there is no window with Pointer Capture";
1442 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001443 case DropReason::NOT_DROPPED: {
1444 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001449 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001450 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001451 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001452 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1453 options.displayId = keyEntry.displayId;
1454 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001458 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001459 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1460 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001461 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001462 options.displayId = motionEntry.displayId;
1463 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 synthesizeCancelationEventsForAllConnectionsLocked(options);
1465 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001466 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1467 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001468 options.displayId = motionEntry.displayId;
1469 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001470 synthesizeCancelationEventsForAllConnectionsLocked(options);
1471 }
1472 break;
1473 }
Chris Yef59a2f42020-10-16 12:55:26 -07001474 case EventEntry::Type::SENSOR: {
1475 break;
1476 }
arthurhungb89ccb02020-12-30 16:19:01 +08001477 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1478 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001479 break;
1480 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001481 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001482 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001483 case EventEntry::Type::CONFIGURATION_CHANGED:
1484 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001485 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001486 break;
1487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489}
1490
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
Prabir Pradhancef936d2021-07-21 16:17:52 +00001495bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001496 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 return false;
1498 }
1499
1500 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001501 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001502 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001503 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1504 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001505 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 return true;
1507}
1508
Prabir Pradhancef936d2021-07-21 16:17:52 +00001509void InputDispatcher::postCommandLocked(Command&& command) {
1510 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511}
1512
1513void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001514 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001515 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001516 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 releaseInboundEventLocked(entry);
1518 }
1519 traceInboundQueueLengthLocked();
1520}
1521
1522void InputDispatcher::releasePendingEventLocked() {
1523 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001525 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527}
1528
Prabir Pradhan24047542023-11-02 17:14:59 +00001529void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001530 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001532 if (DEBUG_DISPATCH_CYCLE) {
1533 ALOGD("Injected inbound event was dropped.");
1534 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 }
1537 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001538 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541}
1542
1543void InputDispatcher::resetKeyRepeatLocked() {
1544 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547}
1548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001550 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551
Michael Wright2e732952014-09-24 13:26:59 -07001552 uint32_t policyFlags = entry->policyFlags &
1553 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001556 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1557 currentTime, entry->deviceId, entry->source,
1558 entry->displayId, policyFlags, entry->action, entry->flags,
1559 entry->keyCode, entry->scanCode, entry->metaState,
1560 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001563 if (mTracer) {
1564 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1565 }
1566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001567 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570}
1571
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001572bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001574 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1575 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
1578 // Reset key repeating in case a keyboard device was added or removed or something.
1579 resetKeyRepeatLocked();
1580
1581 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001582 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1583 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001584 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001585 };
1586 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 return true;
1588}
1589
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001590bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1591 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1593 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1594 entry.deviceId);
1595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596
liushenxiang42232912021-05-21 20:24:09 +08001597 // Reset key repeating in case a keyboard device was disabled or enabled.
1598 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1599 resetKeyRepeatLocked();
1600 }
1601
Michael Wrightfb04fd52022-11-24 22:31:11 +00001602 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001603 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001605
1606 // Remove all active pointers from this device
1607 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1608 touchState.removeAllPointersForDevice(entry.deviceId);
1609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 return true;
1611}
1612
Vishnu Nairad321cd2020-08-20 16:40:21 -07001613void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001614 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001615 if (mPendingEvent != nullptr) {
1616 // Move the pending event to the front of the queue. This will give the chance
1617 // for the pending event to get dispatched to the newly focused window
1618 mInboundQueue.push_front(mPendingEvent);
1619 mPendingEvent = nullptr;
1620 }
1621
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001622 std::unique_ptr<FocusEntry> focusEntry =
1623 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1624 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001625
1626 // This event should go to the front of the queue, but behind all other focus events
1627 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001628 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1629 [](const std::shared_ptr<const EventEntry>& event) {
1630 return event->type == EventEntry::Type::FOCUS;
1631 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001632
1633 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001635}
1636
Prabir Pradhan24047542023-11-02 17:14:59 +00001637void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1638 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001639 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1640 if (connection == nullptr) {
1641 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001642 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001643 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001644 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001645 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001646 std::string reason = std::string("reason=").append(entry->reason);
1647 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001648 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001649}
1650
Prabir Pradhan99987712020-11-10 18:43:05 -08001651void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001652 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001653 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001654 dropReason = DropReason::NOT_DROPPED;
1655
Prabir Pradhan99987712020-11-10 18:43:05 -08001656 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001657 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001658
1659 if (entry->pointerCaptureRequest.enable) {
1660 // Enable Pointer Capture.
1661 if (haveWindowWithPointerCapture &&
1662 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001663 // This can happen if pointer capture is disabled and re-enabled before we notify the
1664 // app of the state change, so there is no need to notify the app.
1665 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1666 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001667 }
1668 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001669 // This can happen if a window requests capture and immediately releases capture.
1670 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001671 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001672 return;
1673 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001674 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1675 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1676 return;
1677 }
1678
Vishnu Nairc519ff72021-01-21 08:23:08 -08001679 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001680 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1681 mWindowTokenWithPointerCapture = token;
1682 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001683 // Disable Pointer Capture.
1684 // We do not check if the sequence number matches for requests to disable Pointer Capture
1685 // for two reasons:
1686 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1687 // to disable capture with the same sequence number: one generated by
1688 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1689 // Capture being disabled in InputReader.
1690 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1691 // actual Pointer Capture state that affects events being generated by input devices is
1692 // in InputReader.
1693 if (!haveWindowWithPointerCapture) {
1694 // Pointer capture was already forcefully disabled because of focus change.
1695 dropReason = DropReason::NOT_DROPPED;
1696 return;
1697 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001698 token = mWindowTokenWithPointerCapture;
1699 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001700 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001701 setPointerCaptureLocked(false);
1702 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001703 }
1704
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001705 auto connection = getConnectionLocked(token);
1706 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001707 // Window has gone away, clean up Pointer Capture state.
1708 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001709 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001710 setPointerCaptureLocked(false);
1711 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001712 return;
1713 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001714 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001715 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001716
1717 dropReason = DropReason::NOT_DROPPED;
1718}
1719
Prabir Pradhan24047542023-11-02 17:14:59 +00001720void InputDispatcher::dispatchTouchModeChangeLocked(
1721 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001722 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001723 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001724 if (windowHandles.empty()) {
1725 return;
1726 }
1727 const std::vector<InputTarget> inputTargets =
1728 getInputTargetsFromWindowHandlesLocked(windowHandles);
1729 if (inputTargets.empty()) {
1730 return;
1731 }
1732 entry->dispatchInProgress = true;
1733 dispatchEventLocked(currentTime, entry, inputTargets);
1734}
1735
1736std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1737 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1738 std::vector<InputTarget> inputTargets;
1739 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001740 const sp<IBinder>& token = handle->getToken();
1741 if (token == nullptr) {
1742 continue;
1743 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001744 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1745 if (connection == nullptr) {
1746 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001747 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001748 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001749 }
1750 return inputTargets;
1751}
1752
Prabir Pradhan24047542023-11-02 17:14:59 +00001753bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001754 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001756 if (!entry->dispatchInProgress) {
1757 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1758 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1759 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1760 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001761 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 // We have seen two identical key downs in a row which indicates that the device
1763 // driver is automatically generating key repeats itself. We take note of the
1764 // repeat here, but we disable our own next key repeat timer since it is clear that
1765 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001766 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1767 // Make sure we don't get key down from a different device. If a different
1768 // device Id has same key pressed down, the new device Id will replace the
1769 // current one to hold the key repeat with repeat count reset.
1770 // In the future when got a KEY_UP on the device id, drop it and do not
1771 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1773 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001774 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 } else {
1776 // Not a repeat. Save key down state in case we do see a repeat later.
1777 resetKeyRepeatLocked();
1778 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1779 }
1780 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001781 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1782 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001783 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001784 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001785 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1786 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 resetKeyRepeatLocked();
1789 }
1790
1791 if (entry->repeatCount == 1) {
1792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1793 } else {
1794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1795 }
1796
1797 entry->dispatchInProgress = true;
1798
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001799 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
1801
1802 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001803 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001805 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 return false; // wait until next wakeup
1807 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001808 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 entry->interceptKeyWakeupTime = 0;
1810 }
1811
1812 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001813 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001815 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001816 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001817
1818 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1819 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1820 };
1821 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001822 // Poke user activity for keys not passed to user
1823 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 return false; // wait for the command to run
1825 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001826 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001828 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001829 if (*dropReason == DropReason::NOT_DROPPED) {
1830 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
1832 }
1833
1834 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001835 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001836 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1838 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001839 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001840 // Poke user activity for undispatched keys
1841 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 return true;
1843 }
1844
1845 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001846 InputEventInjectionResult injectionResult;
1847 sp<WindowInfoHandle> focusedWindow =
1848 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1849 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001850 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 return false;
1852 }
1853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001854 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001855 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 return true;
1857 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001858 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1859
1860 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001861 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1862 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001864 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001865 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001867 if (mTracer) {
1868 ensureEventTraced(*entry);
1869 for (const auto& target : inputTargets) {
1870 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1871 }
1872 }
1873
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 // Dispatch the key.
1875 dispatchEventLocked(currentTime, entry, inputTargets);
1876 return true;
1877}
1878
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001879void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001880 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1881 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1882 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1883 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1884 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1885 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1886 entry.metaState, entry.repeatCount, entry.downTime);
1887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888}
1889
Prabir Pradhancef936d2021-07-21 16:17:52 +00001890void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001891 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001892 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001893 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1894 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1895 "source=0x%x, sensorType=%s",
1896 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001897 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001898 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001899 auto command = [this, entry]() REQUIRES(mLock) {
1900 scoped_unlock unlock(mLock);
1901
1902 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001903 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001904 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001905 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1906 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001907 };
1908 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001909}
1910
1911bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001912 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1913 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001914 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001915 }
Chris Yef59a2f42020-10-16 12:55:26 -07001916 { // acquire lock
1917 std::scoped_lock _l(mLock);
1918
1919 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001920 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001921 if (entry->type == EventEntry::Type::SENSOR) {
1922 it = mInboundQueue.erase(it);
1923 releaseInboundEventLocked(entry);
1924 }
1925 }
1926 }
1927 return true;
1928}
1929
Prabir Pradhan24047542023-11-02 17:14:59 +00001930bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1931 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001932 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001933 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 entry->dispatchInProgress = true;
1937
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001938 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 }
1940
1941 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001942 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001943 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1945 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 return true;
1947 }
1948
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001949 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950
1951 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001952 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001954 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 if (isPointerEvent) {
1956 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001957
1958 if (mDragState &&
1959 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1960 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1961 pilferPointersLocked(mDragState->dragWindow->getToken());
1962 }
1963
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001964 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001965 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001966 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1967 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 } else {
1969 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001970 sp<WindowInfoHandle> focusedWindow =
1971 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1972 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1973 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001974 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1975 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1976 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 return false;
1981 }
1982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001983 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001984 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001985 return true;
1986 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001988 CancelationOptions::Mode mode(
1989 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1990 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001992 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001993 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 return true;
1995 }
1996
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001997 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001998 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00002000 if (mTracer) {
2001 ensureEventTraced(*entry);
2002 for (const auto& target : inputTargets) {
2003 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2004 }
2005 }
2006
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 dispatchEventLocked(currentTime, entry, inputTargets);
2009 return true;
2010}
2011
chaviw98318de2021-05-19 16:45:23 -05002012void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002013 bool isExiting, const int32_t rawX,
2014 const int32_t rawY) {
2015 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002016 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002017 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2018 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002019
2020 enqueueInboundEventLocked(std::move(dragEntry));
2021}
2022
Prabir Pradhan24047542023-11-02 17:14:59 +00002023void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2024 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002025 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2026 if (connection == nullptr) {
2027 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002028 }
arthurhungb89ccb02020-12-30 16:19:01 +08002029 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002030 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002031}
2032
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002033void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002034 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002035 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002036 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002037 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002038 "metaState=0x%x, buttonState=0x%x,"
2039 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002040 prefix, entry.eventTime, entry.deviceId,
2041 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2042 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2043 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2044 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002046 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002047 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002048 "x=%f, y=%f, pressure=%f, size=%f, "
2049 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2050 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002051 i, entry.pointerProperties[i].id,
2052 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002053 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2054 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2055 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2056 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2057 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2058 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2059 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2060 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2061 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064}
2065
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002066void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002067 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002069 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002070 if (DEBUG_DISPATCH_CYCLE) {
2071 ALOGD("dispatchEventToCurrentInputTargets");
2072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002074 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002075
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002080 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002081 std::shared_ptr<Connection> connection = inputTarget.connection;
2082 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
2084}
2085
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002086void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002087 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2088 // If the policy decides to close the app, we will get a channel removal event via
2089 // unregisterInputChannel, and will clean up the connection that way. We are already not
2090 // sending new pointers to the connection when it blocked, but focused events will continue to
2091 // pile up.
2092 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002093 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002094 if (connection->status != Connection::Status::NORMAL) {
2095 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002097 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2098 "application not responding");
2099
2100 sp<WindowInfoHandle> windowHandle;
2101 if (!connection->monitor) {
2102 windowHandle = getWindowHandleLocked(connection->getToken());
2103 if (windowHandle == nullptr) {
2104 // The window that is receiving this ANR was removed, so there is no need to generate
2105 // cancellations, because the cancellations would have already been generated when
2106 // the window was removed.
2107 return;
2108 }
2109 }
2110 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111}
2112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002114 if (DEBUG_FOCUS) {
2115 ALOGD("Resetting ANR timeouts.");
2116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117
2118 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002120 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121}
2122
Tiger Huang721e26f2018-07-24 22:26:19 +08002123/**
2124 * Get the display id that the given event should go to. If this event specifies a valid display id,
2125 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2126 * Focused display is the display that the user most recently interacted with.
2127 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002128int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002129 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002130 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002131 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002132 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2133 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134 break;
2135 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002136 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002137 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2138 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002139 break;
2140 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002141 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002142 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002143 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002144 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002145 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002146 case EventEntry::Type::SENSOR:
2147 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002148 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002149 return ADISPLAY_ID_NONE;
2150 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002151 }
2152 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2153}
2154
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002155bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2156 const char* focusedWindowName) {
2157 if (mAnrTracker.empty()) {
2158 // already processed all events that we waited for
2159 mKeyIsWaitingForEventsTimeout = std::nullopt;
2160 return false;
2161 }
2162
2163 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2164 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002165 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002166 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002167 std::chrono::duration_cast<std::chrono::nanoseconds>(
2168 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002169 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 return true;
2171 }
2172
2173 // We still have pending events, and already started the timer
2174 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2175 return true; // Still waiting
2176 }
2177
2178 // Waited too long, and some connection still hasn't processed all motions
2179 // Just send the key to the focused window
2180 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2181 focusedWindowName);
2182 mKeyIsWaitingForEventsTimeout = std::nullopt;
2183 return false;
2184}
2185
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002187 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002189 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190
Tiger Huang721e26f2018-07-24 22:26:19 +08002191 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002192 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002193 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002194 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2195
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 // If there is no currently focused window and no focused application
2197 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002198 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2199 ALOGI("Dropping %s event because there is no focused window or focused application in "
2200 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002201 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002202 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
2204
Vishnu Nair062a8672021-09-03 16:07:44 -07002205 // Drop key events if requested by input feature
2206 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002207 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002208 }
2209
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2211 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2212 // start interacting with another application via touch (app switch). This code can be removed
2213 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2214 // an app is expected to have a focused window.
2215 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2216 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2217 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002218 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2219 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2220 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002221 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002222 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002223 ALOGW("Waiting because no window has focus but %s may eventually add a "
2224 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002225 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002226 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::PENDING;
2228 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2230 // Already raised ANR. Drop the event
2231 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002232 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002233 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234 } else {
2235 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002236 outInjectionResult = InputEventInjectionResult::PENDING;
2237 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002238 }
2239 }
2240
2241 // we have a valid, non-null focused window
2242 resetNoFocusedWindowTimeoutLocked();
2243
Prabir Pradhan5735a322022-04-11 17:23:34 +00002244 // Verify targeted injection.
2245 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2246 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002247 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2248 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 }
2250
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002251 if (focusedWindowHandle->getInfo()->inputConfig.test(
2252 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002253 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002254 outInjectionResult = InputEventInjectionResult::PENDING;
2255 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002256 }
2257
2258 // If the event is a key event, then we must wait for all previous events to
2259 // complete before delivering it because previous events may have the
2260 // side-effect of transferring focus to a different window and we want to
2261 // ensure that the following keys are sent to the new window.
2262 //
2263 // Suppose the user touches a button in a window then immediately presses "A".
2264 // If the button causes a pop-up window to appear then we want to ensure that
2265 // the "A" key is delivered to the new pop-up window. This is because users
2266 // often anticipate pending UI changes when typing on a keyboard.
2267 // To obtain this behavior, we must serialize key events with respect to all
2268 // prior input events.
2269 if (entry.type == EventEntry::Type::KEY) {
2270 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002271 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002272 outInjectionResult = InputEventInjectionResult::PENDING;
2273 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002277 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2278 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279}
2280
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002281/**
2282 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2283 * that are currently unresponsive.
2284 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002285std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2286 const std::vector<Monitor>& monitors) const {
2287 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002288 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002289 [](const Monitor& monitor) REQUIRES(mLock) {
2290 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002291 if (!connection->responsive) {
2292 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002293 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002294 return false;
2295 }
2296 return true;
2297 });
2298 return responsiveMonitors;
2299}
2300
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002301std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002302 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002303 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002304 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002306 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 // For security reasons, we defer updating the touch state until we are sure that
2308 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 const int32_t displayId = entry.displayId;
2310 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002311 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312
2313 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002314 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002316 // Copy current touch state into tempTouchState.
2317 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2318 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002319 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002320 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002321 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2322 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002323 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002324 }
2325
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002326 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002327
2328 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2329 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2330 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002331 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2332 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002333 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002334 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2335 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002336 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2337 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2338 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002339 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002340
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002341 if (newGesture) {
2342 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002343 }
2344
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002345 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2346 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2347 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
2349
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002350 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002351 if (wasDown) {
2352 // Started hovering, but the device is already down: reject the hover event
2353 LOG(ERROR) << "Got hover event " << entry.getDescription()
2354 << " but the device is already down " << oldState->dump();
2355 outInjectionResult = InputEventInjectionResult::FAILED;
2356 return {};
2357 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002358 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2359 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002360 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002361 }
2362
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2364 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002365 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002366 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002367 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002368 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2369 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002370 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002371 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002372 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002373
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002374 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002375 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002378 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002379 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002381 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002382 }
2383
Prabir Pradhan5735a322022-04-11 17:23:34 +00002384 // Verify targeted injection.
2385 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2386 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002387 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002388 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002389 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002390 }
2391
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002392 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002393 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2395 // New window supports splitting, but we should never split mouse events.
2396 isSplit = !isFromMouse;
2397 } else if (isSplit) {
2398 // New window does not support splitting but we have already split events.
2399 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002400 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2401 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002402 newTouchedWindowHandle = nullptr;
2403 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002404 } else {
2405 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002406 // be delivered to a new window which supports split touch. Pointers from a mouse device
2407 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002408 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002409 }
2410
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002411 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002412 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002414 // Process the foreground window first so that it is the first to receive the event.
2415 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002416 }
2417
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002418 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002419 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2420 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002421 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002422 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002423 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002424 }
2425
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002426 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002427 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002428 continue;
2429 }
2430
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002431 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002432 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002433 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002434 }
2435
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002437 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002438
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002439 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2440 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002441 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002442 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002443
2444 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002445 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002446 }
2447 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002448 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002449 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002450 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002451 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002452
2453 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002454
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002455 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002456 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2457 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002458 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002459 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002460 isDownOrPointerDown
2461 ? std::make_optional(entry.eventTime)
2462 : std::nullopt);
2463 // If this is the pointer going down and the touched window has a wallpaper
2464 // then also add the touched wallpaper windows so they are locked in for the
2465 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2466 // SCROLL because the wallpaper engine only supports touch events. We would need to
2467 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2468 // handle these events.
2469 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002470 windowHandle->getInfo()->inputConfig.test(
2471 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2472 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2473 if (wallpaper != nullptr) {
2474 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2475 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002476 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002477 if (isSplit) {
2478 wallpaperFlags |= InputTarget::Flags::SPLIT;
2479 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002480 tempTouchState.addOrUpdateWindow(wallpaper,
2481 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002482 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002483 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002484 }
2485 }
2486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002488
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002489 // If a window is already pilfering some pointers, give it this new pointer as well and
2490 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2491 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002492 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002493 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002494 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002495 // This window is already pilfering some pointers, and this new pointer is also
2496 // going to it. Therefore, take over this pointer and don't give it to anyone
2497 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002498 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002499 }
2500 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002501
2502 // Restrict all pilfered pointers to the pilfering windows.
2503 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 } else {
2505 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2506
2507 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002508 if (!tempTouchState.isDown(entry.deviceId) &&
2509 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002510 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2511 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2512 << " is not down or we previously dropped the pointer down event in "
2513 << "display " << displayId << ": " << entry.getDescription();
2514 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002515 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002516 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 }
2518
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002519 // If the pointer is not currently hovering, then ignore the event.
2520 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2521 const int32_t pointerId = entry.pointerProperties[0].id;
2522 if (oldState == nullptr ||
2523 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2524 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2525 "display "
2526 << displayId << ": " << entry.getDescription();
2527 outInjectionResult = InputEventInjectionResult::FAILED;
2528 return {};
2529 }
2530 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2531 }
2532
arthurhung6d4bed92021-03-17 11:59:33 +08002533 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002534
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002536 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002537 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002538 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002539 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002540 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002541 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002542 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002543 sp<WindowInfoHandle> newTouchedWindowHandle =
2544 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002545
Prabir Pradhan5735a322022-04-11 17:23:34 +00002546 // Verify targeted injection.
2547 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2548 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002549 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002550 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002551 }
2552
Vishnu Nair062a8672021-09-03 16:07:44 -07002553 // Drop touch events if requested by input feature
2554 if (newTouchedWindowHandle != nullptr &&
2555 shouldDropInput(entry, newTouchedWindowHandle)) {
2556 newTouchedWindowHandle = nullptr;
2557 }
2558
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002559 if (newTouchedWindowHandle != nullptr &&
2560 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002561 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002562 oldTouchedWindowHandle->getName().c_str(),
2563 newTouchedWindowHandle->getName().c_str(), displayId);
2564
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002566 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002567 const PointerProperties& pointer = entry.pointerProperties[0];
2568 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002569
2570 const TouchedWindow& touchedWindow =
2571 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002572 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002573 InputTarget::DispatchMode::SLIPPERY_EXIT,
2574 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002575 touchedWindow.getDownTimeInTarget(entry.deviceId),
2576 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577
2578 // Make a slippery entrance into the new window.
2579 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002580 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002583 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002584 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002585 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002588 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002591 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002592 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002593 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 }
2595
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002596 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2597 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002598 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002599 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002600
2601 // Check if the wallpaper window should deliver the corresponding event.
2602 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002603 tempTouchState, entry.deviceId, pointer, targets);
2604 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002605 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 }
2607 }
Arthur Hung96483742022-11-15 03:30:48 +00002608
2609 // Update the pointerIds for non-splittable when it received pointer down.
2610 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2611 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002612 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002613 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2614 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002615 // Ignore drag window for it should just track one pointer.
2616 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2617 continue;
2618 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002619 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002620 }
2621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 }
2623
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002624 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002625 {
2626 std::vector<TouchedWindow> hoveringWindows =
2627 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2628 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002629 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002630 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2631 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002632 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002633 if (!target) {
2634 continue;
2635 }
2636 // Hardcode to single hovering pointer for now.
2637 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2638 pointerIds.set(entry.pointerProperties[0].id);
2639 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2640 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643
Prabir Pradhan5735a322022-04-11 17:23:34 +00002644 // Ensure that all touched windows are valid for injection.
2645 if (entry.injectionState != nullptr) {
2646 std::string errs;
2647 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002648 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2649 if (err) errs += "\n - " + *err;
2650 }
2651 if (!errs.empty()) {
2652 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002653 "%s:%s",
2654 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002655 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002656 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002657 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002658 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002659
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002660 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2661 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002663 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002664 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002665 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002666 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002667 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002668 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002669 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002670 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002671 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2672 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 }
2675 }
2676 }
2677 }
2678
Harry Cuttsb166c002023-05-09 13:06:05 +00002679 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2680 // only want the system UI to handle these gestures.
2681 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2682 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2683 if (isTouchpadNavGesture) {
2684 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2685 }
2686
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002687 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002688 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002689 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002690 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002691 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002692 continue;
2693 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002694 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002695 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002696 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002697 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002698
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002699 // During targeted injection, only allow owned targets to receive events
2700 std::erase_if(targets, [&](const InputTarget& target) {
2701 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2702 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2703 if (err) {
2704 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2705 << ": " << (*err);
2706 return true;
2707 }
2708 return false;
2709 });
2710
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002711 if (targets.empty()) {
2712 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2713 outInjectionResult = InputEventInjectionResult::FAILED;
2714 return {};
2715 }
2716
2717 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2718 // window that is actually receiving the entire gesture.
2719 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002720 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002721 })) {
2722 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2723 << entry.getDescription();
2724 outInjectionResult = InputEventInjectionResult::FAILED;
2725 return {};
2726 }
2727
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729
Prabir Pradhan502a7252023-12-01 16:11:24 +00002730 // Now that we have generated all of the input targets for this event, reset the dispatch
2731 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002732 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002733 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002734 }
2735
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002736 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002737 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002738 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002739 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002740 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002741 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002742 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002743 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2744 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002745 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2746 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2747 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 }
2749
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002750 // Save changes unless the action was scroll in which case the temporary touch
2751 // state was only valid for this one action.
2752 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002753 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002754 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002755 mTouchStatesByDisplay[displayId] = tempTouchState;
2756 } else {
2757 mTouchStatesByDisplay.erase(displayId);
2758 }
2759 }
2760
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002761 if (tempTouchState.windows.empty()) {
2762 mTouchStatesByDisplay.erase(displayId);
2763 }
2764
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002765 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766}
2767
arthurhung6d4bed92021-03-17 11:59:33 +08002768void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002769 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2770 // have an explicit reason to support it.
2771 constexpr bool isStylus = false;
2772
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002773 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002774 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002775 if (dropWindow) {
2776 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002777 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002778 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002779 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002780 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002781 }
2782 mDragState.reset();
2783}
2784
2785void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002786 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002787 return;
2788 }
2789
arthurhung6d4bed92021-03-17 11:59:33 +08002790 if (!mDragState->isStartDrag) {
2791 mDragState->isStartDrag = true;
2792 mDragState->isStylusButtonDownAtStart =
2793 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2794 }
2795
Arthur Hung54745652022-04-20 07:17:41 +00002796 // Find the pointer index by id.
2797 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002798 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002799 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2800 if (pointerProperties.id == mDragState->pointerId) {
2801 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002802 }
Arthur Hung54745652022-04-20 07:17:41 +00002803 }
arthurhung6d4bed92021-03-17 11:59:33 +08002804
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002805 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002806 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002807 }
2808
2809 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2810 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2811 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2812
2813 switch (maskedAction) {
2814 case AMOTION_EVENT_ACTION_MOVE: {
2815 // Handle the special case : stylus button no longer pressed.
2816 bool isStylusButtonDown =
2817 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2818 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2819 finishDragAndDrop(entry.displayId, x, y);
2820 return;
2821 }
2822
2823 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2824 // until we have an explicit reason to support it.
2825 constexpr bool isStylus = false;
2826
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002827 sp<WindowInfoHandle> hoverWindowHandle =
2828 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2829 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002830 // enqueue drag exit if needed.
2831 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2832 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2833 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002834 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002835 y);
2836 }
2837 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2838 }
2839 // enqueue drag location if needed.
2840 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002841 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002842 }
2843 break;
2844 }
2845
2846 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002847 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002848 break;
2849 }
2850 // The drag pointer is up.
2851 [[fallthrough]];
2852 case AMOTION_EVENT_ACTION_UP:
2853 finishDragAndDrop(entry.displayId, x, y);
2854 break;
2855 case AMOTION_EVENT_ACTION_CANCEL: {
2856 ALOGD("Receiving cancel when drag and drop.");
2857 sendDropWindowCommandLocked(nullptr, 0, 0);
2858 mDragState.reset();
2859 break;
2860 }
arthurhungb89ccb02020-12-30 16:19:01 +08002861 }
2862}
2863
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002864std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2865 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002866 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002867 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002868 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2869 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002870 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2871 return {};
2872 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002873 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002874 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002875 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002876 inputTarget.flags = targetFlags;
2877 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2878 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2879 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2880 if (displayInfoIt != mDisplayInfos.end()) {
2881 inputTarget.displayTransform = displayInfoIt->second.transform;
2882 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002883 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002884 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2885 }
2886 return inputTarget;
2887}
2888
chaviw98318de2021-05-19 16:45:23 -05002889void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002890 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002891 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002892 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002893 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002894 std::vector<InputTarget>::iterator it =
2895 std::find_if(inputTargets.begin(), inputTargets.end(),
2896 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002897 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002898 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002899
chaviw98318de2021-05-19 16:45:23 -05002900 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901
2902 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002903 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002904 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2905 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002906 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002907 return;
2908 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002909 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002910 it = inputTargets.end() - 1;
2911 }
2912
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002913 if (it->flags != targetFlags) {
2914 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2915 }
2916 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2917 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2918 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2919 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002920}
2921
2922void InputDispatcher::addPointerWindowTargetLocked(
2923 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002924 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2925 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2926 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002927 if (pointerIds.none()) {
2928 for (const auto& target : inputTargets) {
2929 LOG(INFO) << "Target: " << target;
2930 }
2931 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2932 return;
2933 }
2934 std::vector<InputTarget>::iterator it =
2935 std::find_if(inputTargets.begin(), inputTargets.end(),
2936 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002937 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002938 });
2939
2940 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2941 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2942 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2943 // input targets for hovering pointers and for touching pointers.
2944 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2945 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002946 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002947 // Force the code below to create a new input target
2948 it = inputTargets.end();
2949 }
2950
2951 const WindowInfo* windowInfo = windowHandle->getInfo();
2952
2953 if (it == inputTargets.end()) {
2954 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002955 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2956 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002957 if (!target) {
2958 return;
2959 }
2960 inputTargets.push_back(*target);
2961 it = inputTargets.end() - 1;
2962 }
2963
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002964 if (it->dispatchMode != dispatchMode) {
2965 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2966 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2967 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002968 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002969 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2970 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002971 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002972 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002973 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002974 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2975 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002976
chaviw1ff3d1e2020-07-01 15:53:47 -07002977 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978}
2979
Michael Wright3dd60e22019-03-27 22:06:44 +00002980void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002981 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002982 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2983 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002984
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002985 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002986 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002987 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2988 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002989 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2990 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002991 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002992 target.setDefaultPointerTransform(target.displayTransform);
2993 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995}
2996
Robert Carrc9bf1d32020-04-13 17:21:08 -07002997/**
2998 * Indicate whether one window handle should be considered as obscuring
2999 * another window handle. We only check a few preconditions. Actually
3000 * checking the bounds is left to the caller.
3001 */
chaviw98318de2021-05-19 16:45:23 -05003002static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3003 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003004 // Compare by token so cloned layers aren't counted
3005 if (haveSameToken(windowHandle, otherHandle)) {
3006 return false;
3007 }
3008 auto info = windowHandle->getInfo();
3009 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003010 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003011 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003012 } else if (otherInfo->alpha == 0 &&
3013 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003014 // Those act as if they were invisible, so we don't need to flag them.
3015 // We do want to potentially flag touchable windows even if they have 0
3016 // opacity, since they can consume touches and alter the effects of the
3017 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003019 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3020 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003021 } else if (info->ownerUid == otherInfo->ownerUid) {
3022 // If ownerUid is the same we don't generate occlusion events as there
3023 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003024 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003025 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003026 return false;
3027 } else if (otherInfo->displayId != info->displayId) {
3028 return false;
3029 }
3030 return true;
3031}
3032
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003033/**
3034 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3035 * untrusted, one should check:
3036 *
3037 * 1. If result.hasBlockingOcclusion is true.
3038 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3039 * BLOCK_UNTRUSTED.
3040 *
3041 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3042 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3043 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3044 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3045 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3046 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3047 *
3048 * If neither of those is true, then it means the touch can be allowed.
3049 */
3050InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003051 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3052 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003053 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003054 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003055 TouchOcclusionInfo info;
3056 info.hasBlockingOcclusion = false;
3057 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003058 info.obscuringUid = gui::Uid::INVALID;
3059 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003060 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 if (windowHandle == otherHandle) {
3062 break; // All future windows are below us. Exit early.
3063 }
chaviw98318de2021-05-19 16:45:23 -05003064 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003065 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3066 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003067 if (DEBUG_TOUCH_OCCLUSION) {
3068 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003069 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003070 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003071 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3072 // we perform the checks below to see if the touch can be propagated or not based on the
3073 // window's touch occlusion mode
3074 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3075 info.hasBlockingOcclusion = true;
3076 info.obscuringUid = otherInfo->ownerUid;
3077 info.obscuringPackage = otherInfo->packageName;
3078 break;
3079 }
3080 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003081 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082 float opacity =
3083 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3084 // Given windows A and B:
3085 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3086 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3087 opacityByUid[uid] = opacity;
3088 if (opacity > info.obscuringOpacity) {
3089 info.obscuringOpacity = opacity;
3090 info.obscuringUid = uid;
3091 info.obscuringPackage = otherInfo->packageName;
3092 }
3093 }
3094 }
3095 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003096 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003097 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003098 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003099 return info;
3100}
3101
chaviw98318de2021-05-19 16:45:23 -05003102std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003103 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003104 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003105 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3106 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3107 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003108 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003109 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003110 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3111 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003112 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3113 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3114 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003115 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003116}
3117
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003118bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3119 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003120 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3121 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003122 return false;
3123 }
3124 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003125 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003126 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003127 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003128 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3129 return false;
3130 }
3131 return true;
3132}
3133
chaviw98318de2021-05-19 16:45:23 -05003134bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003137 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3138 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003139 if (windowHandle == otherHandle) {
3140 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
chaviw98318de2021-05-19 16:45:23 -05003142 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003143 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003144 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 return true;
3146 }
3147 }
3148 return false;
3149}
3150
chaviw98318de2021-05-19 16:45:23 -05003151bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003152 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003153 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3154 const WindowInfo* windowInfo = windowHandle->getInfo();
3155 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003156 if (windowHandle == otherHandle) {
3157 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003158 }
chaviw98318de2021-05-19 16:45:23 -05003159 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003160 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003161 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003162 return true;
3163 }
3164 }
3165 return false;
3166}
3167
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003168std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003169 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003170 if (applicationHandle != nullptr) {
3171 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003172 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 } else {
3174 return applicationHandle->getName();
3175 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003176 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003177 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003179 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181}
3182
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003183void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003184 if (!isUserActivityEvent(eventEntry)) {
3185 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003186 return;
3187 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003188
3189 const int32_t eventType = getUserActivityEventType(eventEntry);
3190 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3191 // Note that we're directly getting the time diff between the current event and the previous
3192 // event. This is assuming that the first user event always happens at a timestamp that is
3193 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3194 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3195 // value than the potential first user activity event time, so this is ok.
3196 std::chrono::nanoseconds timeSinceLastEvent =
3197 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3198 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3199 return;
3200 }
3201 }
3202
Tiger Huang721e26f2018-07-24 22:26:19 +08003203 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003204 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003205 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003206 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003207 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003208 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003209 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211 }
3212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003213 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003214 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003215 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3216 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 return;
3218 }
Josep del Riob3981622023-04-18 15:49:45 +00003219 if (windowDisablingUserActivityInfo != nullptr) {
3220 if (DEBUG_DISPATCH_CYCLE) {
3221 ALOGD("Not poking user activity: disabled by window '%s'.",
3222 windowDisablingUserActivityInfo->name.c_str());
3223 }
3224 return;
3225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003228 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003229 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3230 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 return;
3232 }
Josep del Riob3981622023-04-18 15:49:45 +00003233 // If the key code is unknown, we don't consider it user activity
3234 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3235 return;
3236 }
3237 // Don't inhibit events that were intercepted or are not passed to
3238 // the apps, like system shortcuts
3239 if (windowDisablingUserActivityInfo != nullptr &&
3240 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3241 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3242 if (DEBUG_DISPATCH_CYCLE) {
3243 ALOGD("Not poking user activity: disabled by window '%s'.",
3244 windowDisablingUserActivityInfo->name.c_str());
3245 }
3246 return;
3247 }
3248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003251 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003252 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003253 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003254 break;
3255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003258 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003259 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3260 REQUIRES(mLock) {
3261 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003262 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003263 };
3264 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265}
3266
3267void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003268 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003269 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003270 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003271 ATRACE_NAME_IF(ATRACE_ENABLED(),
3272 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3273 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003274 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003276 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003278 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003279 inputTarget.getPointerInfoString().c_str());
3280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
3282 // Skip this event if the connection status is not normal.
3283 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003284 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003285 if (DEBUG_DISPATCH_CYCLE) {
3286 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003287 connection->getInputChannelName().c_str(),
3288 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 return;
3291 }
3292
3293 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003295 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003297 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003299 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003300 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003301 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3302 logDispatchStateLocked();
3303 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3304 "target on connection "
3305 << connection->getInputChannelName() << " for "
3306 << originalMotionEntry.getDescription();
3307 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003309 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003310 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 if (!splitMotionEntry) {
3312 return; // split event was dropped
3313 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003314 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3315 std::string reason = std::string("reason=pointer cancel on split window");
3316 android_log_event_list(LOGTAG_INPUT_CANCEL)
3317 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3318 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003319 if (DEBUG_FOCUS) {
3320 ALOGD("channel '%s' ~ Split motion event.",
3321 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003322 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003323 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003324 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3325 std::move(splitMotionEntry),
3326 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 return;
3328 }
3329 }
3330
3331 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003332 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3333 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334}
3335
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003336void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3337 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3338 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003339 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003340 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3341 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003342 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003343
hongzuo liu95785e22022-09-06 02:51:35 +00003344 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003346 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
3348 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003349 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 startDispatchCycleLocked(currentTime, connection);
3351 }
3352}
3353
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003354void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003355 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003356 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003357 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3358 eventEntry->type == EventEntry::Type::MOTION;
3359 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3360 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3361 << inputTarget << " connection: " << connection->getInputChannelName()
3362 << " entry: " << eventEntry->getDescription();
3363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 // This is a new event.
3365 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003366 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003367 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3368 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003370 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3371 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003372 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003374 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003375 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003376 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3377 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003378 LOG(WARNING) << "channel " << connection->getInputChannelName()
3379 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380 return; // skip the inconsistent event
3381 }
3382 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003385 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003386 std::shared_ptr<const MotionEntry> resolvedMotion =
3387 std::static_pointer_cast<const MotionEntry>(eventEntry);
3388 {
3389 // Determine the resolved motion entry.
3390 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3391 int32_t resolvedAction = motionEntry.action;
3392 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003394 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003395 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003396 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003397 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003398 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003399 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003400 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003401 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003402 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003403 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3404 }
3405 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3406 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3407 motionEntry.displayId)) {
3408 if (DEBUG_DISPATCH_CYCLE) {
3409 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3410 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3411 "enter event";
3412 }
3413 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3414 }
3415
3416 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3417 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3418 }
3419 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3420 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3421 }
3422 if (dispatchEntry->targetFlags.test(
3423 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3424 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3425 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003426 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3427 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3428 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003429
3430 dispatchEntry->resolvedFlags = resolvedFlags;
3431 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003432 std::optional<std::vector<PointerProperties>> usingProperties;
3433 std::optional<std::vector<PointerCoords>> usingCoords;
3434 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3435 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3436 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3437 // the dispatcher, and therefore the coordinates of this event are currently
3438 // incorrect. These events should use the coordinates of the last dispatched
3439 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3440 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3441 std::optional<std::pair<std::vector<PointerProperties>,
3442 std::vector<PointerCoords>>>
3443 pointerInfo =
3444 connection->inputState.getPointersOfLastEvent(motionEntry,
3445 hovering);
3446 if (pointerInfo) {
3447 usingProperties = pointerInfo->first;
3448 usingCoords = pointerInfo->second;
3449 }
3450 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003451 // Generate a new MotionEntry with a new eventId using the resolved action and
3452 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003453 resolvedMotion = std::make_shared<
3454 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3455 motionEntry.eventTime, motionEntry.deviceId,
3456 motionEntry.source, motionEntry.displayId,
3457 motionEntry.policyFlags, resolvedAction,
3458 motionEntry.actionButton, resolvedFlags,
3459 motionEntry.metaState, motionEntry.buttonState,
3460 motionEntry.classification, motionEntry.edgeFlags,
3461 motionEntry.xPrecision, motionEntry.yPrecision,
3462 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3463 motionEntry.downTime,
3464 usingProperties.value_or(motionEntry.pointerProperties),
3465 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003466 if (ATRACE_ENABLED()) {
3467 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3468 ") to MotionEvent(id=0x%" PRIx32 ").",
3469 motionEntry.id, resolvedMotion->id);
3470 ATRACE_NAME(message.c_str());
3471 }
3472
3473 // Set the resolved motion entry in the DispatchEntry.
3474 dispatchEntry->eventEntry = resolvedMotion;
3475 eventEntry = resolvedMotion;
3476 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003479 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3480 // devices being active at the same time in the same window, so if a new device is
3481 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003482 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003483 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003484 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003485 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003486 << connection->getInputChannelName() << " with event "
3487 << cancelEvent->getDescription();
3488 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003489 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003490 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003491
3492 // Send these cancel events to the queue before sending the event from the new
3493 // device.
3494 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3495 }
3496
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003497 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003499 LOG(WARNING) << "channel " << connection->getInputChannelName()
3500 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003501 return; // skip the inconsistent event
3502 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003503 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003504 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003505 // Skip reporting pointer down outside focus to the policy.
3506 break;
3507 }
3508
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003509 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003510 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511
3512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003514 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003515 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003516 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3517 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003518 break;
3519 }
Chris Yef59a2f42020-10-16 12:55:26 -07003520 case EventEntry::Type::SENSOR: {
3521 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3522 break;
3523 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003524 case EventEntry::Type::CONFIGURATION_CHANGED:
3525 case EventEntry::Type::DEVICE_RESET: {
3526 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003527 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003528 break;
3529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 }
3531
3532 // Remember that we are waiting for this dispatch to complete.
3533 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003534 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536
3537 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003538 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003539 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003540}
3541
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003542/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003543 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003544 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003545 * The first role is to log input interaction with windows, which helps determine what the user was
3546 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3547 * that user started interacting with launcher window, as well as any other window that received
3548 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3549 * when the set of tokens that received the event changes. It is not logged again as long as the
3550 * user is interacting with the same windows.
3551 *
3552 * The second role is to track input device activity for metrics collection. For each input event,
3553 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3554 * input_interaction logs, the device interaction is reported even when the set of interaction
3555 * tokens do not change.
3556 *
3557 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3558 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003559 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003560void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3561 const std::vector<InputTarget>& targets) {
3562 int32_t deviceId;
3563 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003564 // Skip ACTION_UP events, and all events other than keys and motions
3565 if (entry.type == EventEntry::Type::KEY) {
3566 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3567 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3568 return;
3569 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003570 deviceId = keyEntry.deviceId;
3571 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003572 } else if (entry.type == EventEntry::Type::MOTION) {
3573 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3574 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003575 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3576 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003577 return;
3578 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003579 deviceId = motionEntry.deviceId;
3580 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 } else {
3582 return; // Not a key or a motion
3583 }
3584
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003585 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003586 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003587 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003588 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003589 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003590 continue; // Skip windows that receive ACTION_OUTSIDE
3591 }
3592
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003593 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003594 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003595 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003596 if (target.windowHandle) {
3597 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3598 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003599 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003600
3601 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3602 REQUIRES(mLock) {
3603 scoped_unlock unlock(mLock);
3604 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3605 };
3606 postCommandLocked(std::move(command));
3607
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003608 if (newConnectionTokens == mInteractionConnectionTokens) {
3609 return; // no change
3610 }
3611 mInteractionConnectionTokens = newConnectionTokens;
3612
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003613 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003614 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003615 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003616 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003617 std::string message = "Interaction with: " + targetList;
3618 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003619 message += "<none>";
3620 }
3621 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3622}
3623
chaviwfd6d3512019-03-25 13:23:49 -07003624void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003625 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003626 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003627 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3628 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003629 return;
3630 }
3631
Vishnu Nairc519ff72021-01-21 08:23:08 -08003632 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003633 if (focusedToken == token) {
3634 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003635 return;
3636 }
3637
Prabir Pradhancef936d2021-07-21 16:17:52 +00003638 auto command = [this, token]() REQUIRES(mLock) {
3639 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003640 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003641 };
3642 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643}
3644
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003645status_t InputDispatcher::publishMotionEvent(Connection& connection,
3646 DispatchEntry& dispatchEntry) const {
3647 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3648 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3649
3650 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003651 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003652
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003653 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003654 // Set the X and Y offset and X and Y scale depending on the input source.
3655 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003656 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003657 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3658 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003659 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003660 scaledCoords[i] = motionEntry.pointerCoords[i];
3661 // Don't apply window scale here since we don't want scale to affect raw
3662 // coordinates. The scale will be sent back to the client and applied
3663 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003664 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665 }
3666 usingCoords = scaledCoords;
3667 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003668 }
3669
3670 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3671
3672 // Publish the motion event.
3673 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003674 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3675 motionEntry.source, motionEntry.displayId, std::move(hmac),
3676 motionEntry.action, motionEntry.actionButton,
3677 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3678 motionEntry.metaState, motionEntry.buttonState,
3679 motionEntry.classification, dispatchEntry.transform,
3680 motionEntry.xPrecision, motionEntry.yPrecision,
3681 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3682 dispatchEntry.rawTransform, motionEntry.downTime,
3683 motionEntry.eventTime, motionEntry.getPointerCount(),
3684 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003685}
3686
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003688 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003689 ATRACE_NAME_IF(ATRACE_ENABLED(),
3690 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3691 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003692 if (DEBUG_DISPATCH_CYCLE) {
3693 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003696 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003697 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003699 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003700 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701
3702 // Publish the event.
3703 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3705 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003706 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003707 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3708 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003709 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003710 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3711 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003716 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3717 keyEntry.deviceId, keyEntry.source,
3718 keyEntry.displayId, std::move(hmac),
3719 keyEntry.action, dispatchEntry->resolvedFlags,
3720 keyEntry.keyCode, keyEntry.scanCode,
3721 keyEntry.metaState, keyEntry.repeatCount,
3722 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003723 if (mTracer) {
3724 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3725 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
3728
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003729 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003731 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3732 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003733 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003734 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003735 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003736 if (mTracer) {
3737 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3738 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 break;
3740 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003741
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003742 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003743 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003744 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003745 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003746 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003747 break;
3748 }
3749
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003750 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3751 const TouchModeEntry& touchModeEntry =
3752 static_cast<const TouchModeEntry&>(eventEntry);
3753 status = connection->inputPublisher
3754 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3755 touchModeEntry.inTouchMode);
3756
3757 break;
3758 }
3759
Prabir Pradhan99987712020-11-10 18:43:05 -08003760 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3761 const auto& captureEntry =
3762 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3763 status = connection->inputPublisher
3764 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003765 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003766 break;
3767 }
3768
arthurhungb89ccb02020-12-30 16:19:01 +08003769 case EventEntry::Type::DRAG: {
3770 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3771 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3772 dragEntry.id, dragEntry.x,
3773 dragEntry.y,
3774 dragEntry.isExiting);
3775 break;
3776 }
3777
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003778 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003779 case EventEntry::Type::DEVICE_RESET:
3780 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003781 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003782 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786
3787 // Check the result.
3788 if (status) {
3789 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003790 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 "This is unexpected because the wait queue is empty, so the pipe "
3793 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003794 "event to it, status=%s(%d)",
3795 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3796 status);
Harry Cutts33476232023-01-30 19:57:29 +00003797 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 } else {
3799 // Pipe is full and we are waiting for the app to finish process some events
3800 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003801 if (DEBUG_DISPATCH_CYCLE) {
3802 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3803 "waiting for the application to catch up",
3804 connection->getInputChannelName().c_str());
3805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807 } else {
3808 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003809 "status=%s(%d)",
3810 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3811 status);
Harry Cutts33476232023-01-30 19:57:29 +00003812 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814 return;
3815 }
3816
3817 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003818 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3819 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3820 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003821 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003822 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003823 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003825 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 }
3827}
3828
chaviw09c8d2d2020-08-24 15:48:26 -07003829std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3830 size_t size;
3831 switch (event.type) {
3832 case VerifiedInputEvent::Type::KEY: {
3833 size = sizeof(VerifiedKeyEvent);
3834 break;
3835 }
3836 case VerifiedInputEvent::Type::MOTION: {
3837 size = sizeof(VerifiedMotionEvent);
3838 break;
3839 }
3840 }
3841 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3842 return mHmacKeyManager.sign(start, size);
3843}
3844
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003845const std::array<uint8_t, 32> InputDispatcher::getSignature(
3846 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003847 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003848 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003849 // Only sign events up and down events as the purely move events
3850 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003851 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003852 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003853
3854 VerifiedMotionEvent verifiedEvent =
3855 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3856 verifiedEvent.actionMasked = actionMasked;
3857 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3858 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003859}
3860
3861const std::array<uint8_t, 32> InputDispatcher::getSignature(
3862 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3863 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3864 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003865 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003866}
3867
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003869 const std::shared_ptr<Connection>& connection,
3870 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003871 if (DEBUG_DISPATCH_CYCLE) {
3872 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3873 connection->getInputChannelName().c_str(), seq, toString(handled));
3874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003876 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 return;
3878 }
3879
3880 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003881 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3882 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3883 };
3884 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885}
3886
3887void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003888 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003889 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003890 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003891 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3892 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
3895 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003896 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003897 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003898 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003899 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900
3901 // The connection appears to be unrecoverably broken.
3902 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003903 if (connection->status == Connection::Status::NORMAL) {
3904 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
3906 if (notify) {
3907 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003908 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3909 connection->getInputChannelName().c_str());
3910
3911 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003912 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003913 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003914 };
3915 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 }
3917 }
3918}
3919
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003920void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003921 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003922 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003923 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 }
3925}
3926
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003927void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003929 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931}
3932
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003933int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3934 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003935 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003936 if (connection == nullptr) {
3937 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3938 connectionToken.get(), events);
3939 return 0; // remove the callback
3940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003942 bool notify;
3943 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3944 if (!(events & ALOOPER_EVENT_INPUT)) {
3945 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3946 "events=0x%x",
3947 connection->getInputChannelName().c_str(), events);
3948 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 }
3950
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003951 nsecs_t currentTime = now();
3952 bool gotOne = false;
3953 status_t status = OK;
3954 for (;;) {
3955 Result<InputPublisher::ConsumerResponse> result =
3956 connection->inputPublisher.receiveConsumerResponse();
3957 if (!result.ok()) {
3958 status = result.error().code();
3959 break;
3960 }
3961
3962 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3963 const InputPublisher::Finished& finish =
3964 std::get<InputPublisher::Finished>(*result);
3965 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3966 finish.consumeTime);
3967 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003968 if (shouldReportMetricsForConnection(*connection)) {
3969 const InputPublisher::Timeline& timeline =
3970 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003971 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3972 connection->getToken(),
3973 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003974 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003975 }
3976 gotOne = true;
3977 }
3978 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003979 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003980 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 return 1;
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003985 notify = status != DEAD_OBJECT || !connection->monitor;
3986 if (notify) {
3987 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3988 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3989 status);
3990 }
3991 } else {
3992 // Monitor channels are never explicitly unregistered.
3993 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003994 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003995 notify = !connection->monitor && stillHaveWindowHandle;
3996 if (notify) {
3997 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3998 connection->getInputChannelName().c_str(), events);
3999 }
4000 }
4001
4002 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004003 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004004 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005}
4006
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004009 // Cancel windows (i.e. non-monitors).
4010 // A channel must have at least one window to receive any input. If a window was removed, the
4011 // event streams directed to the window will already have been canceled during window removal.
4012 // So there is no need to generate cancellations for connections without any windows.
4013 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4014 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4015 // through a non-touched window if there are more than one window for an input channel.
4016 if (cancelPointers) {
4017 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4018 if (options.displayId.has_value() && options.displayId != displayId) {
4019 continue;
4020 }
4021 for (const auto& touchedWindow : touchState.windows) {
4022 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4023 }
4024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004026 // Follow up by generating cancellations for all windows, because we don't explicitly track
4027 // the windows that have an ongoing focus event stream.
4028 if (cancelNonPointers) {
4029 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4030 for (const auto& windowHandle : handles) {
4031 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4032 }
4033 }
4034 }
4035
4036 // Cancel monitors.
4037 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038}
4039
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004041 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004042 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004043 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004044 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4045 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004046 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004047 }
4048}
4049
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004050void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4051 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4052 const std::shared_ptr<Connection>& connection) {
4053 if (windowHandle == nullptr) {
4054 LOG(FATAL) << __func__ << ": Window handle must not be null";
4055 }
4056 if (connection) {
4057 // The connection can be optionally provided to avoid multiple lookups.
4058 if (windowHandle->getToken() != connection->getToken()) {
4059 LOG(FATAL) << __func__
4060 << ": Wrong connection provided for window: " << windowHandle->getName();
4061 }
4062 }
4063
4064 std::shared_ptr<Connection> resolvedConnection =
4065 connection ? connection : getConnectionLocked(windowHandle->getToken());
4066 if (!resolvedConnection) {
4067 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4068 return;
4069 }
4070 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4071}
4072
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004074 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4075 const sp<WindowInfoHandle>& window) {
4076 if (!connection->monitor && window == nullptr) {
4077 LOG(FATAL) << __func__
4078 << ": Cannot send event to non-monitor channel without a window - channel: "
4079 << connection->getInputChannelName();
4080 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004081 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 return;
4083 }
4084
4085 nsecs_t currentTime = now();
4086
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004087 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004088 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004090 if (cancelationEvents.empty()) {
4091 return;
4092 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004093
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004094 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4095 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004096 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004098 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004099 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100
Arthur Hungb3307ee2021-10-14 10:57:37 +00004101 std::string reason = std::string("reason=").append(options.reason);
4102 android_log_event_list(LOGTAG_INPUT_CANCEL)
4103 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4104
hongzuo liu95785e22022-09-06 02:51:35 +00004105 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004106 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004107 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004108 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004109
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004110 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004111 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004112 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004113
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004114 switch (cancelationEventEntry->type) {
4115 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004116 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004117 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004118 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4119 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004120 } else {
4121 targets.emplace_back(fallbackTarget);
4122 }
4123 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004124 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004126 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004127 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004128 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004129 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004130 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004131 pointerIndex++) {
4132 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4133 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004134 if (mDragState && mDragState->dragWindow->getToken() == token &&
4135 pointerIds.test(mDragState->pointerId)) {
4136 LOG(INFO) << __func__
4137 << ": Canceling drag and drop because the pointers for the drag "
4138 "window are being canceled.";
4139 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4140 mDragState.reset();
4141 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004142 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4143 ftl::Flags<InputTarget::Flags>(), pointerIds,
4144 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004145 } else {
4146 targets.emplace_back(fallbackTarget);
4147 const auto it = mDisplayInfos.find(motionEntry.displayId);
4148 if (it != mDisplayInfos.end()) {
4149 targets.back().displayTransform = it->second.transform;
4150 targets.back().setDefaultPointerTransform(it->second.transform);
4151 }
4152 }
4153 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004154 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004156 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004157 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004158 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4159 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004160 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004161 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004162 break;
4163 }
4164 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004165 case EventEntry::Type::DEVICE_RESET:
4166 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004167 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004168 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004169 break;
4170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004173 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004174 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004176
hongzuo liu95785e22022-09-06 02:51:35 +00004177 // If the outbound queue was previously empty, start the dispatch cycle going.
4178 if (wasEmpty && !connection->outboundQueue.empty()) {
4179 startDispatchCycleLocked(currentTime, connection);
4180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181}
4182
Svet Ganov5d3bc372020-01-26 23:11:07 -08004183void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004184 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004185 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004186 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004187 return;
4188 }
4189
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004190 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004191 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004192
4193 if (downEvents.empty()) {
4194 return;
4195 }
4196
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004197 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004198 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4199 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004200 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004202 const auto [_, touchedWindowState, displayId] =
4203 findTouchStateWindowAndDisplayLocked(connection->getToken());
4204 if (touchedWindowState == nullptr) {
4205 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4206 }
4207 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004208
hongzuo liu95785e22022-09-06 02:51:35 +00004209 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004210 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004211 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004212 switch (downEventEntry->type) {
4213 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004214 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4215 if (windowHandle != nullptr) {
4216 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004217 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004218 pointerIndex++) {
4219 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4220 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004221 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4222 targetFlags, pointerIds, motionEntry.downTime,
4223 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004224 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004225 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004226 const auto it = mDisplayInfos.find(motionEntry.displayId);
4227 if (it != mDisplayInfos.end()) {
4228 targets.back().displayTransform = it->second.transform;
4229 targets.back().setDefaultPointerTransform(it->second.transform);
4230 }
4231 }
4232 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004233 break;
4234 }
4235
4236 case EventEntry::Type::KEY:
4237 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004238 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004239 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004240 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004241 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004242 case EventEntry::Type::SENSOR:
4243 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004244 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004245 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004246 break;
4247 }
4248 }
4249
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004250 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004251 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004252 }
4253
hongzuo liu95785e22022-09-06 02:51:35 +00004254 // If the outbound queue was previously empty, start the dispatch cycle going.
4255 if (wasEmpty && !connection->outboundQueue.empty()) {
4256 startDispatchCycleLocked(downTime, connection);
4257 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004258}
4259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004260std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004261 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4262 nsecs_t splitDownTime) {
4263 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264
4265 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004266 std::vector<PointerProperties> splitPointerProperties;
4267 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004269 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 uint32_t splitPointerCount = 0;
4271
4272 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004275 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004277 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004279 splitPointerProperties.push_back(pointerProperties);
4280 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 splitPointerCount += 1;
4282 }
4283 }
4284
4285 if (splitPointerCount != pointerIds.count()) {
4286 // This is bad. We are missing some of the pointers that we expected to deliver.
4287 // Most likely this indicates that we received an ACTION_MOVE events that has
4288 // different pointer ids than we expected based on the previous ACTION_DOWN
4289 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4290 // in this way.
4291 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004292 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004293 "a broken sequence of pointer ids from the input device: %s",
4294 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004295 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 }
4297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004298 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4301 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004302 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004304 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004306 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 if (pointerIds.count() == 1) {
4308 // The first/last pointer went down/up.
4309 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004311 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4312 ? AMOTION_EVENT_ACTION_CANCEL
4313 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 } else {
4315 // A secondary pointer went down/up.
4316 uint32_t splitPointerIndex = 0;
4317 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4318 splitPointerIndex += 1;
4319 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004320 action = maskedAction |
4321 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323 } else {
4324 // An unrelated pointer changed.
4325 action = AMOTION_EVENT_ACTION_MOVE;
4326 }
4327 }
4328
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004329 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4330 logDispatchStateLocked();
4331 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4332 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4333 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004334 }
4335
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004336 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004337 ATRACE_NAME_IF(ATRACE_ENABLED(),
4338 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4339 ").",
4340 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004342 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4343 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004344 originalMotionEntry.deviceId, originalMotionEntry.source,
4345 originalMotionEntry.displayId,
4346 originalMotionEntry.policyFlags, action,
4347 originalMotionEntry.actionButton,
4348 originalMotionEntry.flags, originalMotionEntry.metaState,
4349 originalMotionEntry.buttonState,
4350 originalMotionEntry.classification,
4351 originalMotionEntry.edgeFlags,
4352 originalMotionEntry.xPrecision,
4353 originalMotionEntry.yPrecision,
4354 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004355 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004356 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 return splitMotionEntry;
4359}
4360
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004361void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4362 std::scoped_lock _l(mLock);
4363 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4364}
4365
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004366void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004367 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004368 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370
Antonio Kantekf16f2832021-09-28 04:39:20 +00004371 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004375 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004376 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004377 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 } // release lock
4379
4380 if (needWake) {
4381 mLooper->wake();
4382 }
4383}
4384
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004385void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004386 ALOGD_IF(debugInboundEventDetails(),
4387 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4388 ", deviceId=%d, source=%s, displayId=%" PRId32
4389 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4390 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4392 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4393 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004394 Result<void> keyCheck = validateKeyEvent(args.action);
4395 if (!keyCheck.ok()) {
4396 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 return;
4398 }
4399
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400 uint32_t policyFlags = args.policyFlags;
4401 int32_t flags = args.flags;
4402 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004403 // InputDispatcher tracks and generates key repeats on behalf of
4404 // whatever notifies it, so repeatCount should always be set to 0
4405 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4407 policyFlags |= POLICY_FLAG_VIRTUAL;
4408 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 if (policyFlags & POLICY_FLAG_FUNCTION) {
4411 metaState |= AMETA_FUNCTION_ON;
4412 }
4413
4414 policyFlags |= POLICY_FLAG_TRUSTED;
4415
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004416 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004418 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4419 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4420 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421
Michael Wright2b3c3302018-03-02 17:19:13 +00004422 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004423 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004424 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4425 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004426 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Antonio Kantekf16f2832021-09-28 04:39:20 +00004429 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 { // acquire lock
4431 mLock.lock();
4432
4433 if (shouldSendKeyToInputFilterLocked(args)) {
4434 mLock.unlock();
4435
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004436 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004437 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 return; // event was consumed by the filter
4439 }
4440
4441 mLock.lock();
4442 }
4443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004444 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004445 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4446 args.deviceId, args.source, args.displayId, policyFlags,
4447 args.action, flags, keyCode, args.scanCode, metaState,
4448 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004449 if (mTracer) {
4450 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004453 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 mLock.unlock();
4455 } // release lock
4456
4457 if (needWake) {
4458 mLooper->wake();
4459 }
4460}
4461
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 return mInputFilterEnabled;
4464}
4465
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004466void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004467 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004468 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004469 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004470 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004471 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4472 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004473 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4474 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4475 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4476 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4477 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004478 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004479 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4480 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 i, args.pointerProperties[i].id,
4482 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4483 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4484 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4485 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4486 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4487 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4488 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4489 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4490 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4491 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004494
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004495 Result<void> motionCheck =
4496 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4497 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004498 if (!motionCheck.ok()) {
4499 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4500 return;
4501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004503 if (DEBUG_VERIFY_EVENTS) {
4504 auto [it, _] =
4505 mVerifiersByDisplay.try_emplace(args.displayId,
4506 StringPrintf("display %" PRId32, args.displayId));
4507 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004508 it->second.processMovement(args.deviceId, args.source, args.action,
4509 args.getPointerCount(), args.pointerProperties.data(),
4510 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004511 if (!result.ok()) {
4512 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4513 }
4514 }
4515
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004516 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004518
4519 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004520 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4521 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004522 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4523 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004524 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Antonio Kantekf16f2832021-09-28 04:39:20 +00004527 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 { // acquire lock
4529 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004530 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4531 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4532 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004534 if (touchStateIt != mTouchStatesByDisplay.end()) {
4535 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004536 if (touchState.hasTouchingPointers(args.deviceId) ||
4537 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004538 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4539 }
4540 }
4541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
4543 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004544 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004545 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004546 displayTransform = it->second.transform;
4547 }
4548
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 mLock.unlock();
4550
4551 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004552 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4553 args.action, args.actionButton, args.flags, args.edgeFlags,
4554 args.metaState, args.buttonState, args.classification,
4555 displayTransform, args.xPrecision, args.yPrecision,
4556 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004557 args.downTime, args.eventTime, args.getPointerCount(),
4558 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
4560 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004561 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 return; // event was consumed by the filter
4563 }
4564
4565 mLock.lock();
4566 }
4567
4568 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004569 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004570 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4571 args.deviceId, args.source, args.displayId,
4572 policyFlags, args.action, args.actionButton,
4573 args.flags, args.metaState, args.buttonState,
4574 args.classification, args.edgeFlags, args.xPrecision,
4575 args.yPrecision, args.xCursorPosition,
4576 args.yCursorPosition, args.downTime,
4577 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004578 if (mTracer) {
4579 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004582 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4583 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004584 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004585 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004586 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4587 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4588 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004589 }
4590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004591 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 mLock.unlock();
4593 } // release lock
4594
4595 if (needWake) {
4596 mLooper->wake();
4597 }
4598}
4599
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004600void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004601 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004602 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4603 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004604 args.id, args.eventTime, args.deviceId, args.source,
4605 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004606 }
Chris Yef59a2f42020-10-16 12:55:26 -07004607
Antonio Kantekf16f2832021-09-28 04:39:20 +00004608 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004609 { // acquire lock
4610 mLock.lock();
4611
4612 // Just enqueue a new sensor event.
4613 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004614 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4615 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4616 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004617
4618 needWake = enqueueInboundEventLocked(std::move(newEntry));
4619 mLock.unlock();
4620 } // release lock
4621
4622 if (needWake) {
4623 mLooper->wake();
4624 }
4625}
4626
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004627void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004628 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004629 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4630 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004631 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004632 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004633}
4634
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004636 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637}
4638
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004639void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004640 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004641 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4642 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004643 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004648 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649}
4650
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004651void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004652 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004653 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4654 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
Antonio Kantekf16f2832021-09-28 04:39:20 +00004657 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004659 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004661 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004662 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004663 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004664
4665 for (auto& [_, verifier] : mVerifiersByDisplay) {
4666 verifier.resetDevice(args.deviceId);
4667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 } // release lock
4669
4670 if (needWake) {
4671 mLooper->wake();
4672 }
4673}
4674
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004675void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004676 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004677 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4678 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004679 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004680
Antonio Kantekf16f2832021-09-28 04:39:20 +00004681 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004682 { // acquire lock
4683 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004684 auto entry =
4685 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004686 needWake = enqueueInboundEventLocked(std::move(entry));
4687 } // release lock
4688
4689 if (needWake) {
4690 mLooper->wake();
4691 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004692}
4693
Prabir Pradhan5735a322022-04-11 17:23:34 +00004694InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004695 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004696 InputEventInjectionSync syncMode,
4697 std::chrono::milliseconds timeout,
4698 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004699 Result<void> eventValidation = validateInputEvent(*event);
4700 if (!eventValidation.ok()) {
4701 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4702 return InputEventInjectionResult::FAILED;
4703 }
4704
Prabir Pradhan65613802023-02-22 23:36:58 +00004705 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004706 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4707 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4708 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4709 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004710 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004711 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
Prabir Pradhan5735a322022-04-11 17:23:34 +00004713 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004715 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004716 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4717 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4718 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4719 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4720 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004721 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004722 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004723 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004724 }
4725
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004726 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4727 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4728
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004729 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004731 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004732 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004733 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004734 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004735 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4736 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4737 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004738 int32_t keyCode = incomingKey.getKeyCode();
4739 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004740 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004741 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004742 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4743 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4744 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4747 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004748 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004749
4750 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4751 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004752 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4754 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4755 std::to_string(t.duration().count()).c_str());
4756 }
4757 }
4758
4759 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004760 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004761 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4762 incomingKey.getEventTime(), resolvedDeviceId,
4763 incomingKey.getSource(), incomingKey.getDisplayId(),
4764 policyFlags, action, flags, keyCode,
4765 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004766 incomingKey.getRepeatCount(),
4767 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004768 if (mTracer) {
4769 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4770 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004771 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004772 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 }
4774
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004775 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004776 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004777 const bool isPointerEvent =
4778 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4779 // If a pointer event has no displayId specified, inject it to the default display.
4780 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4781 ? ADISPLAY_ID_DEFAULT
4782 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004783 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784
4785 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004786 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004788 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4789 motionEvent.getAction(), eventTime,
4790 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4792 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4793 std::to_string(t.duration().count()).c_str());
4794 }
4795 }
4796
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004797 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4798 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4799 }
4800
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004801 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004802 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004803 const size_t pointerCount = motionEvent.getPointerCount();
4804 const std::vector<PointerProperties>
4805 pointerProperties(motionEvent.getPointerProperties(),
4806 motionEvent.getPointerProperties() + pointerCount);
4807
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004808 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004809 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004810 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4811 *sampleEventTimes, resolvedDeviceId,
4812 motionEvent.getSource(), displayId, policyFlags,
4813 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004814 motionEvent.getActionButton(), flags,
4815 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004816 motionEvent.getButtonState(),
4817 motionEvent.getClassification(),
4818 motionEvent.getEdgeFlags(),
4819 motionEvent.getXPrecision(),
4820 motionEvent.getYPrecision(),
4821 motionEvent.getRawXCursorPosition(),
4822 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004823 motionEvent.getDownTime(), pointerProperties,
4824 std::vector<PointerCoords>(samplePointerCoords,
4825 samplePointerCoords +
4826 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004827 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004828 if (mTracer) {
4829 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4830 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004831 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004832 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004833 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004834 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004835 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004836 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4837 resolvedDeviceId, motionEvent.getSource(), displayId,
4838 policyFlags, motionEvent.getAction(),
4839 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004840 motionEvent.getMetaState(), motionEvent.getButtonState(),
4841 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4842 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4843 motionEvent.getRawXCursorPosition(),
4844 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4845 pointerProperties,
4846 std::vector<PointerCoords>(samplePointerCoords,
4847 samplePointerCoords +
4848 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004849 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4850 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004851 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004852 }
4853 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004857 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004858 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
4860
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004862 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004863 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004864 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004865 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004866 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004867 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869
4870 mLock.unlock();
4871
4872 if (needWake) {
4873 mLooper->wake();
4874 }
4875
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004876 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004878 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004880 if (syncMode == InputEventInjectionSync::NONE) {
4881 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 } else {
4883 for (;;) {
4884 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004885 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 break;
4887 }
4888
4889 nsecs_t remainingTimeout = endTime - now();
4890 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004891 if (DEBUG_INJECTION) {
4892 ALOGD("injectInputEvent - Timed out waiting for injection result "
4893 "to become available.");
4894 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 break;
4897 }
4898
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004899 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 }
4901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4903 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004905 if (DEBUG_INJECTION) {
4906 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4907 injectionState->pendingForegroundDispatches);
4908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 nsecs_t remainingTimeout = endTime - now();
4910 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004911 if (DEBUG_INJECTION) {
4912 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4913 "dispatches to finish.");
4914 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004915 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 break;
4917 }
4918
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004919 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 }
4921 }
4922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 } // release lock
4924
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004925 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004926 LOG(INFO) << "injectInputEvent - Finished with result "
4927 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929
4930 return injectionResult;
4931}
4932
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004933std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004934 std::array<uint8_t, 32> calculatedHmac;
4935 std::unique_ptr<VerifiedInputEvent> result;
4936 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004937 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004938 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4939 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4940 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004941 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004942 break;
4943 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004944 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004945 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4946 VerifiedMotionEvent verifiedMotionEvent =
4947 verifiedMotionEventFromMotionEvent(motionEvent);
4948 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004949 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004950 break;
4951 }
4952 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004953 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004954 return nullptr;
4955 }
4956 }
4957 if (calculatedHmac == INVALID_HMAC) {
4958 return nullptr;
4959 }
tyiu1573a672023-02-21 22:38:32 +00004960 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004961 return nullptr;
4962 }
4963 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004964}
4965
Prabir Pradhan24047542023-11-02 17:14:59 +00004966void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004967 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004968 if (!entry.injectionState) {
4969 // Not an injected event.
4970 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004972
4973 InjectionState& injectionState = *entry.injectionState;
4974 if (DEBUG_INJECTION) {
4975 LOG(INFO) << "Setting input event injection result to "
4976 << ftl::enum_string(injectionResult);
4977 }
4978
4979 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4980 // Log the outcome since the injector did not wait for the injection result.
4981 switch (injectionResult) {
4982 case InputEventInjectionResult::SUCCEEDED:
4983 ALOGV("Asynchronous input event injection succeeded.");
4984 break;
4985 case InputEventInjectionResult::TARGET_MISMATCH:
4986 ALOGV("Asynchronous input event injection target mismatch.");
4987 break;
4988 case InputEventInjectionResult::FAILED:
4989 ALOGW("Asynchronous input event injection failed.");
4990 break;
4991 case InputEventInjectionResult::TIMED_OUT:
4992 ALOGW("Asynchronous input event injection timed out.");
4993 break;
4994 case InputEventInjectionResult::PENDING:
4995 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4996 break;
4997 }
4998 }
4999
5000 injectionState.injectionResult = injectionResult;
5001 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002}
5003
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005004void InputDispatcher::transformMotionEntryForInjectionLocked(
5005 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005006 // Input injection works in the logical display coordinate space, but the input pipeline works
5007 // display space, so we need to transform the injected events accordingly.
5008 const auto it = mDisplayInfos.find(entry.displayId);
5009 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005010 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005011
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005012 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5013 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5014 const vec2 cursor =
5015 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5016 {entry.xCursorPosition, entry.yCursorPosition});
5017 entry.xCursorPosition = cursor.x;
5018 entry.yCursorPosition = cursor.y;
5019 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005020 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005021 entry.pointerCoords[i] =
5022 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5023 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005024 }
5025}
5026
Prabir Pradhan24047542023-11-02 17:14:59 +00005027void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005028 if (entry.injectionState) {
5029 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 }
5031}
5032
Prabir Pradhan24047542023-11-02 17:14:59 +00005033void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005034 if (entry.injectionState) {
5035 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005037 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005038 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040 }
5041}
5042
chaviw98318de2021-05-19 16:45:23 -05005043const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005044 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005045 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005046 auto it = mWindowHandlesByDisplay.find(displayId);
5047 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005048}
5049
chaviw98318de2021-05-19 16:45:23 -05005050sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005051 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005052 if (windowHandleToken == nullptr) {
5053 return nullptr;
5054 }
5055
Prabir Pradhan16463382023-10-12 23:03:19 +00005056 if (!displayId) {
5057 // Look through all displays.
5058 for (auto& it : mWindowHandlesByDisplay) {
5059 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5060 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5061 if (windowHandle->getToken() == windowHandleToken) {
5062 return windowHandle;
5063 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005066 return nullptr;
5067 }
5068
Prabir Pradhan16463382023-10-12 23:03:19 +00005069 // Only look through the requested display.
5070 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005071 if (windowHandle->getToken() == windowHandleToken) {
5072 return windowHandle;
5073 }
5074 }
5075 return nullptr;
5076}
5077
chaviw98318de2021-05-19 16:45:23 -05005078sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5079 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005080 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005081 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5082 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005083 if (handle->getId() == windowHandle->getId() &&
5084 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005085 if (windowHandle->getInfo()->displayId != it.first) {
5086 ALOGE("Found window %s in display %" PRId32
5087 ", but it should belong to display %" PRId32,
5088 windowHandle->getName().c_str(), it.first,
5089 windowHandle->getInfo()->displayId);
5090 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005091 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 }
5094 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005095 return nullptr;
5096}
5097
chaviw98318de2021-05-19 16:45:23 -05005098sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005099 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5100 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101}
5102
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005103ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5104 auto displayInfoIt = mDisplayInfos.find(displayId);
5105 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5106 : kIdentityTransform;
5107}
5108
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005109bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5110 const MotionEntry& motionEntry) const {
5111 const WindowInfo& info = *window->getInfo();
5112
5113 // Skip spy window targets that are not valid for targeted injection.
5114 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005115 return false;
5116 }
5117
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005118 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5119 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5120 return false;
5121 }
5122
5123 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5124 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5125 window->getName().c_str());
5126 return false;
5127 }
5128
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005129 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005131 ALOGW("Not sending touch to %s because there's no corresponding connection",
5132 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005133 return false;
5134 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005135
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005136 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005137 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005138 return false;
5139 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005140
5141 // Drop events that can't be trusted due to occlusion
5142 const auto [x, y] = resolveTouchedPosition(motionEntry);
5143 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5144 if (!isTouchTrustedLocked(occlusionInfo)) {
5145 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005146 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005147 for (const auto& log : occlusionInfo.debugInfo) {
5148 ALOGD("%s", log.c_str());
5149 }
5150 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005151 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5152 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005153 return false;
5154 }
5155
5156 // Drop touch events if requested by input feature
5157 if (shouldDropInput(motionEntry, window)) {
5158 return false;
5159 }
5160
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005161 // Ignore touches if stylus is down anywhere on screen
5162 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5163 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5164 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5165 return false;
5166 }
5167
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005168 return true;
5169}
5170
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005172 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5173 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005174 // Remove all handles on a display if there are no windows left.
5175 mWindowHandlesByDisplay.erase(displayId);
5176 return;
5177 }
5178
5179 // Since we compare the pointer of input window handles across window updates, we need
5180 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005181 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5182 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5183 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005184 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005185 }
5186
chaviw98318de2021-05-19 16:45:23 -05005187 std::vector<sp<WindowInfoHandle>> newHandles;
5188 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005189 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005190 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005191 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005192 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005193 const bool canReceiveInput =
5194 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5195 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005196 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005197 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005198 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005199 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005200 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005201 }
5202
5203 if (info->displayId != displayId) {
5204 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5205 handle->getName().c_str(), displayId, info->displayId);
5206 continue;
5207 }
5208
Robert Carredd13602020-04-13 17:24:34 -07005209 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5210 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005211 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005212 oldHandle->updateFrom(handle);
5213 newHandles.push_back(oldHandle);
5214 } else {
5215 newHandles.push_back(handle);
5216 }
5217 }
5218
5219 // Insert or replace
5220 mWindowHandlesByDisplay[displayId] = newHandles;
5221}
5222
Arthur Hungb92218b2018-08-14 12:00:21 +08005223/**
5224 * Called from InputManagerService, update window handle list by displayId that can receive input.
5225 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5226 * If set an empty list, remove all handles from the specific display.
5227 * For focused handle, check if need to change and send a cancel event to previous one.
5228 * For removed handle, check if need to send a cancel event if already in touch.
5229 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005230void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005231 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005232 if (DEBUG_FOCUS) {
5233 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005234 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005235 windowList += iwh->getName() + " ";
5236 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005237 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239
Prabir Pradhand65552b2021-10-07 11:23:50 -07005240 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005241 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005242 const WindowInfo& info = *window->getInfo();
5243
5244 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005245 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005246 if (noInputWindow && window->getToken() != nullptr) {
5247 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5248 window->getName().c_str());
5249 window->releaseChannel();
5250 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005251
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005252 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005253 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5254 !info.inputConfig.test(
5255 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005256 "%s has feature SPY, but is not a trusted overlay.",
5257 window->getName().c_str());
5258
Prabir Pradhand65552b2021-10-07 11:23:50 -07005259 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005260 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5261 !info.inputConfig.test(
5262 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005263 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5264 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005265 }
5266
Arthur Hung72d8dc32020-03-28 00:48:39 +00005267 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005268 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005269 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
chaviw98318de2021-05-19 16:45:23 -05005271 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005272
chaviw98318de2021-05-19 16:45:23 -05005273 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005274
Vishnu Nairc519ff72021-01-21 08:23:08 -08005275 std::optional<FocusResolver::FocusChanges> changes =
5276 mFocusResolver.setInputWindows(displayId, windowHandles);
5277 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005278 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005281 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5282 mTouchStatesByDisplay.find(displayId);
5283 if (stateIt != mTouchStatesByDisplay.end()) {
5284 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005285 for (size_t i = 0; i < state.windows.size();) {
5286 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005287 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005288 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5289 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005290 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5291 "touched window was removed");
5292 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5293 // Since we are about to drop the touch, cancel the events for the wallpaper as
5294 // well.
5295 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5296 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5297 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5298 if (const auto& ww = state.getWallpaperWindow(); ww) {
5299 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005302 state.windows.erase(state.windows.begin() + i);
5303 } else {
5304 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 }
5306 }
arthurhungb89ccb02020-12-30 16:19:01 +08005307
arthurhung6d4bed92021-03-17 11:59:33 +08005308 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005309 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005310 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005311 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005312 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005313 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5314 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005315 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005316 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005317 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005318
Arthur Hung72d8dc32020-03-28 00:48:39 +00005319 // Release information for windows that are no longer present.
5320 // This ensures that unused input channels are released promptly.
5321 // Otherwise, they might stick around until the window handle is destroyed
5322 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005323 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005324 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005325 if (DEBUG_FOCUS) {
5326 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005327 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005328 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005329 }
chaviw291d88a2019-02-14 10:33:58 -08005330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331}
5332
5333void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005334 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005335 if (DEBUG_FOCUS) {
5336 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5337 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5338 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005339 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005340 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005341 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 } // release lock
5343
5344 // Wake up poll loop since it may need to make new input dispatching choices.
5345 mLooper->wake();
5346}
5347
Vishnu Nair599f1412021-06-21 10:39:58 -07005348void InputDispatcher::setFocusedApplicationLocked(
5349 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5350 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5351 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5352
5353 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5354 return; // This application is already focused. No need to wake up or change anything.
5355 }
5356
5357 // Set the new application handle.
5358 if (inputApplicationHandle != nullptr) {
5359 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5360 } else {
5361 mFocusedApplicationHandlesByDisplay.erase(displayId);
5362 }
5363
5364 // No matter what the old focused application was, stop waiting on it because it is
5365 // no longer focused.
5366 resetNoFocusedWindowTimeoutLocked();
5367}
5368
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005369void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5370 if (interval.count() < 0) {
5371 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5372 }
5373 std::scoped_lock _l(mLock);
5374 mMinTimeBetweenUserActivityPokes = interval;
5375}
5376
Tiger Huang721e26f2018-07-24 22:26:19 +08005377/**
5378 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5379 * the display not specified.
5380 *
5381 * We track any unreleased events for each window. If a window loses the ability to receive the
5382 * released event, we will send a cancel event to it. So when the focused display is changed, we
5383 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5384 * display. The display-specified events won't be affected.
5385 */
5386void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005387 if (DEBUG_FOCUS) {
5388 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5389 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005390 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005391 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005392
5393 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005394 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005395 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005396 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005397 const auto windowHandle =
5398 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5399 if (windowHandle == nullptr) {
5400 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005402 CancelationOptions
5403 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5404 "The display which contains this window no longer has focus.");
5405 options.displayId = ADISPLAY_ID_NONE;
5406 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005407 }
5408 mFocusedDisplayId = displayId;
5409
Chris Ye3c2d6f52020-08-09 10:39:48 -07005410 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005411 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005412 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005413
Vishnu Nairad321cd2020-08-20 16:40:21 -07005414 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005415 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005417 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005418 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005419 }
5420 }
5421 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005422 } // release lock
5423
5424 // Wake up poll loop since it may need to make new input dispatching choices.
5425 mLooper->wake();
5426}
5427
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005429 if (DEBUG_FOCUS) {
5430 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432
5433 bool changed;
5434 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005435 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436
5437 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5438 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005439 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 }
5441
5442 if (mDispatchEnabled && !enabled) {
5443 resetAndDropEverythingLocked("dispatcher is being disabled");
5444 }
5445
5446 mDispatchEnabled = enabled;
5447 mDispatchFrozen = frozen;
5448 changed = true;
5449 } else {
5450 changed = false;
5451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 } // release lock
5453
5454 if (changed) {
5455 // Wake up poll loop since it may need to make new input dispatching choices.
5456 mLooper->wake();
5457 }
5458}
5459
5460void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005461 if (DEBUG_FOCUS) {
5462 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464
5465 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005466 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467
5468 if (mInputFilterEnabled == enabled) {
5469 return;
5470 }
5471
5472 mInputFilterEnabled = enabled;
5473 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5474 } // release lock
5475
5476 // Wake up poll loop since there might be work to do to drop everything.
5477 mLooper->wake();
5478}
5479
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005480bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005481 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005482 bool needWake = false;
5483 {
5484 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005485 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005486 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005487 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005488 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5489 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005490 mTouchModePerDisplay.count(displayId) == 0
5491 ? "not set"
5492 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5493
Antonio Kantek15beb512022-06-13 22:35:41 +00005494 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5495 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005496 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005497 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005498 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005499 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5500 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005501 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005502 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005503 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005504 return false;
5505 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005506 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005507 mTouchModePerDisplay[displayId] = inTouchMode;
5508 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5509 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005510 needWake = enqueueInboundEventLocked(std::move(entry));
5511 } // release lock
5512
5513 if (needWake) {
5514 mLooper->wake();
5515 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005516 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005517}
5518
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005519bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005520 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5521 if (focusedToken == nullptr) {
5522 return false;
5523 }
5524 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5525 return isWindowOwnedBy(windowHandle, pid, uid);
5526}
5527
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005528bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005529 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5530 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5531 const sp<WindowInfoHandle> windowHandle =
5532 getWindowHandleLocked(connectionToken);
5533 return isWindowOwnedBy(windowHandle, pid, uid);
5534 }) != mInteractionConnectionTokens.end();
5535}
5536
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005537void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5538 if (opacity < 0 || opacity > 1) {
5539 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5540 return;
5541 }
5542
5543 std::scoped_lock lock(mLock);
5544 mMaximumObscuringOpacityForTouch = opacity;
5545}
5546
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005547std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5548InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005549 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5550 for (TouchedWindow& w : state.windows) {
5551 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005552 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005553 }
5554 }
5555 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005556 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005557}
5558
Prabir Pradhan367f3432024-02-13 23:05:58 +00005559bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5560 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005561 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005562 if (DEBUG_FOCUS) {
5563 ALOGD("Trivial transfer to same window.");
5564 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005565 return true;
5566 }
5567
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570
Arthur Hungabbb9d82021-09-01 14:52:30 +00005571 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005572 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005573
Arthur Hungabbb9d82021-09-01 14:52:30 +00005574 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005575 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 return false;
5577 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005578 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5579 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005580 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5581 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005582 return false;
5583 }
5584 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005585
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005586 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5587 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5588 if (!toWindowHandle) {
5589 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005590 return false;
5591 }
5592
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005593 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005594 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005595 touchedWindow->windowHandle->getName().c_str(),
5596 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 }
5598
Arthur Hungabbb9d82021-09-01 14:52:30 +00005599 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005600 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005601 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005602 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603
Arthur Hungabbb9d82021-09-01 14:52:30 +00005604 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005605 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005606 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005607 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005608 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005609 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005610 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005611 // Transferring touch focus using this API should not effect the focused window.
5612 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005613 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005614 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615
Arthur Hungabbb9d82021-09-01 14:52:30 +00005616 // Store the dragging window.
5617 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005618 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005619 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5620 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005621 return false;
5622 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005623 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005624 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005625 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627
Arthur Hungabbb9d82021-09-01 14:52:30 +00005628 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005629 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5630 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005631 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005632 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005633 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5634 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005635 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005636 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5637 newTargetFlags);
5638
5639 // Check if the wallpaper window should deliver the corresponding event.
5640 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005641 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 } // release lock
5644
5645 // Wake up poll loop since it may need to make new input dispatching choices.
5646 mLooper->wake();
5647 return true;
5648}
5649
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005650/**
5651 * Get the touched foreground window on the given display.
5652 * Return null if there are no windows touched on that display, or if more than one foreground
5653 * window is being touched.
5654 */
5655sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5656 auto stateIt = mTouchStatesByDisplay.find(displayId);
5657 if (stateIt == mTouchStatesByDisplay.end()) {
5658 ALOGI("No touch state on display %" PRId32, displayId);
5659 return nullptr;
5660 }
5661
5662 const TouchState& state = stateIt->second;
5663 sp<WindowInfoHandle> touchedForegroundWindow;
5664 // If multiple foreground windows are touched, return nullptr
5665 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005666 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005667 if (touchedForegroundWindow != nullptr) {
5668 ALOGI("Two or more foreground windows: %s and %s",
5669 touchedForegroundWindow->getName().c_str(),
5670 window.windowHandle->getName().c_str());
5671 return nullptr;
5672 }
5673 touchedForegroundWindow = window.windowHandle;
5674 }
5675 }
5676 return touchedForegroundWindow;
5677}
5678
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005679// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005680bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5681 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005682 sp<IBinder> fromToken;
5683 { // acquire lock
5684 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005685 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005686 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005687 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5688 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005689 return false;
5690 }
5691
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005692 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5693 if (from == nullptr) {
5694 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5695 return false;
5696 }
5697
5698 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005699 } // release lock
5700
Prabir Pradhan367f3432024-02-13 23:05:58 +00005701 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005702}
5703
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005705 if (DEBUG_FOCUS) {
5706 ALOGD("Resetting and dropping all events (%s).", reason);
5707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
Michael Wrightfb04fd52022-11-24 22:31:11 +00005709 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 synthesizeCancelationEventsForAllConnectionsLocked(options);
5711
5712 resetKeyRepeatLocked();
5713 releasePendingEventLocked();
5714 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005715 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005717 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005718 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719}
5720
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005721void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005722 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723 dumpDispatchStateLocked(dump);
5724
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005725 std::istringstream stream(dump);
5726 std::string line;
5727
5728 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005729 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731}
5732
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005733std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005734 std::string dump;
5735
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005736 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5737 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005738
5739 std::string windowName = "None";
5740 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005741 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005742 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5743 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5744 : "token has capture without window";
5745 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005746 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005747
5748 return dump;
5749}
5750
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005751void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005752 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5753 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5754 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005755 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756
Tiger Huang721e26f2018-07-24 22:26:19 +08005757 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5758 dump += StringPrintf(INDENT "FocusedApplications:\n");
5759 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5760 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005761 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005762 const std::chrono::duration timeout =
5763 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005764 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005765 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005766 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005769 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005771
Vishnu Nairc519ff72021-01-21 08:23:08 -08005772 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005773 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005775 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005776 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005777 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005778 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5779 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
arthurhung6d4bed92021-03-17 11:59:33 +08005785 if (mDragState) {
5786 dump += StringPrintf(INDENT "DragState:\n");
5787 mDragState->dump(dump, INDENT2);
5788 }
5789
Arthur Hungb92218b2018-08-14 12:00:21 +08005790 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005791 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5792 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5793 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5794 const auto& displayInfo = it->second;
5795 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5796 displayInfo.logicalHeight);
5797 displayInfo.transform.dump(dump, "transform", INDENT4);
5798 } else {
5799 dump += INDENT2 "No DisplayInfo found!\n";
5800 }
5801
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005802 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005803 dump += INDENT2 "Windows:\n";
5804 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005805 dump += StringPrintf(INDENT3 "%zu: %s", i,
5806 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005807 }
5808 } else {
5809 dump += INDENT2 "Windows: <none>\n";
5810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 }
5812 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005813 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005816 if (!mGlobalMonitorsByDisplay.empty()) {
5817 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5818 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005819 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005822 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 }
5824
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005825 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826
5827 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005828 if (!mRecentQueue.empty()) {
5829 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005830 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005831 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005832 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005833 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005834 }
5835 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005836 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838
5839 // Dump event currently being dispatched.
5840 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += INDENT "PendingEvent:\n";
5842 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005843 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005844 dump += StringPrintf(", age=%" PRId64 "ms\n",
5845 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005847 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848 }
5849
5850 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005851 if (!mInboundQueue.empty()) {
5852 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005853 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005854 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005855 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005856 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 }
5858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005859 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 }
5861
Prabir Pradhancef936d2021-07-21 16:17:52 +00005862 if (!mCommandQueue.empty()) {
5863 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5864 } else {
5865 dump += INDENT "CommandQueue: <empty>\n";
5866 }
5867
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005868 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005869 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005870 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005871 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005872 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005873 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005874 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005875 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005876 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005878 if (!connection->outboundQueue.empty()) {
5879 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5880 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005881 dump += dumpQueue(connection->outboundQueue, currentTime);
5882
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005884 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 }
5886
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005887 if (!connection->waitQueue.empty()) {
5888 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5889 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005890 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005892 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005894 std::string inputStateDump = streamableToString(connection->inputState);
5895 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005896 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005897 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899 }
5900 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005901 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 }
5903
Antonio Kantek15beb512022-06-13 22:35:41 +00005904 if (!mTouchModePerDisplay.empty()) {
5905 dump += INDENT "TouchModePerDisplay:\n";
5906 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5907 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5908 std::to_string(touchMode).c_str());
5909 }
5910 } else {
5911 dump += INDENT "TouchModePerDisplay: <none>\n";
5912 }
5913
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005914 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005915 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5916 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5917 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005918 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005919 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005920 dump += INDENT "InputTracer: ";
5921 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922}
5923
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005924void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005925 const size_t numMonitors = monitors.size();
5926 for (size_t i = 0; i < numMonitors; i++) {
5927 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005928 const std::shared_ptr<Connection>& connection = monitor.connection;
5929 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005930 dump += "\n";
5931 }
5932}
5933
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005934class LooperEventCallback : public LooperCallback {
5935public:
5936 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5937 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5938
5939private:
5940 std::function<int(int events)> mCallback;
5941};
5942
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005943Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005944 if (DEBUG_CHANNEL_CREATION) {
5945 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005948 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005949 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005950 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005951
5952 if (result) {
5953 return base::Error(result) << "Failed to open input channel pair with name " << name;
5954 }
5955
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005957 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005958 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005959 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005960 std::shared_ptr<Connection> connection =
5961 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5962 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005964 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5965 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005966 ALOGE("Created a new connection, but the token %p is already known", token.get());
5967 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005968
5969 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5970 this, std::placeholders::_1, token);
5971
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005972 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005973 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 } // release lock
5975
5976 // Wake the looper because some connections have changed.
5977 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005978 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979}
5980
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005981Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005982 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005983 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005984 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005985 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005986 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005987 if (result) {
5988 return base::Error(result) << "Failed to open input channel pair with name " << name;
5989 }
5990
Michael Wright3dd60e22019-03-27 22:06:44 +00005991 { // acquire lock
5992 std::scoped_lock _l(mLock);
5993
5994 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005995 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5996 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005997 }
5998
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005999 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006000 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006001 std::shared_ptr<Connection> connection =
6002 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6003 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006004
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006005 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6006 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006007 ALOGE("Created a new connection, but the token %p is already known", token.get());
6008 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006009
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006010 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6011 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006012
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006013 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006014
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006015 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006016 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006017 }
Garfield Tan15601662020-09-22 15:32:38 -07006018
Michael Wright3dd60e22019-03-27 22:06:44 +00006019 // Wake the looper because some connections have changed.
6020 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006021 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006022}
6023
Garfield Tan15601662020-09-22 15:32:38 -07006024status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006026 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027
Harry Cutts33476232023-01-30 19:57:29 +00006028 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 if (status) {
6030 return status;
6031 }
6032 } // release lock
6033
6034 // Wake the poll loop because removing the connection may have changed the current
6035 // synchronization state.
6036 mLooper->wake();
6037 return OK;
6038}
6039
Garfield Tan15601662020-09-22 15:32:38 -07006040status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6041 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006042 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006043 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006044 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 return BAD_VALUE;
6046 }
6047
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006048 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006049
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006051 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 }
6053
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006054 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
6056 nsecs_t currentTime = now();
6057 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6058
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006059 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 return OK;
6061}
6062
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006063void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006064 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6065 auto& [displayId, monitors] = *it;
6066 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006067 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006068 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006069
Michael Wright3dd60e22019-03-27 22:06:44 +00006070 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006072 } else {
6073 ++it;
6074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
6076}
6077
Michael Wright3dd60e22019-03-27 22:06:44 +00006078status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006079 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006080 return pilferPointersLocked(token);
6081}
Michael Wright3dd60e22019-03-27 22:06:44 +00006082
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006083status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006084 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6085 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006086 LOG(WARNING)
6087 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006088 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006089 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006090
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006091 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006092 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006093 LOG(WARNING)
6094 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6095 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006096 return BAD_VALUE;
6097 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006098 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006099 if (deviceIds.empty()) {
6100 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006101 return BAD_VALUE;
6102 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006103
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006104 for (const DeviceId deviceId : deviceIds) {
6105 TouchState& state = *statePtr;
6106 TouchedWindow& window = *windowPtr;
6107 // Send cancel events to all the input channels we're stealing from.
6108 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6109 "input channel stole pointer stream");
6110 options.deviceId = deviceId;
6111 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006112 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6113 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006114 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006115
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006116 std::string canceledWindows;
6117 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006118 if (w.windowHandle->getToken() != token) {
6119 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006120 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006121 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006122 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006123 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006124 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006125 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006126 << " is stealing input gesture for device " << deviceId << " from "
6127 << canceledWindows;
6128
6129 // Prevent the gesture from being sent to any other windows.
6130 // This only blocks relevant pointers to be sent to other windows
6131 window.addPilferingPointers(deviceId, pointerIds);
6132
6133 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006134 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006135 return OK;
6136}
6137
Prabir Pradhan99987712020-11-10 18:43:05 -08006138void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6139 { // acquire lock
6140 std::scoped_lock _l(mLock);
6141 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006142 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006143 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6144 windowHandle != nullptr ? windowHandle->getName().c_str()
6145 : "token without window");
6146 }
6147
Vishnu Nairc519ff72021-01-21 08:23:08 -08006148 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006149 if (focusedToken != windowToken) {
6150 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6151 enabled ? "enable" : "disable");
6152 return;
6153 }
6154
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006155 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006156 ALOGW("Ignoring request to %s Pointer Capture: "
6157 "window has %s requested pointer capture.",
6158 enabled ? "enable" : "disable", enabled ? "already" : "not");
6159 return;
6160 }
6161
Christine Franksb768bb42021-11-29 12:11:31 -08006162 if (enabled) {
6163 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6164 mIneligibleDisplaysForPointerCapture.end(),
6165 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6166 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6167 return;
6168 }
6169 }
6170
Prabir Pradhan99987712020-11-10 18:43:05 -08006171 setPointerCaptureLocked(enabled);
6172 } // release lock
6173
6174 // Wake the thread to process command entries.
6175 mLooper->wake();
6176}
6177
Christine Franksb768bb42021-11-29 12:11:31 -08006178void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6179 { // acquire lock
6180 std::scoped_lock _l(mLock);
6181 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6182 if (!isEligible) {
6183 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6184 }
6185 } // release lock
6186}
6187
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006188std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006189 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006190 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006191 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006192 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006193 }
6194 }
6195 }
6196 return std::nullopt;
6197}
6198
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006199std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6200 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006201 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006202 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006203 }
6204
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006205 for (const auto& [token, connection] : mConnectionsByToken) {
6206 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006207 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208 }
6209 }
Robert Carr4e670e52018-08-15 13:26:12 -07006210
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006211 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212}
6213
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006214std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006215 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006216 if (connection == nullptr) {
6217 return "<nullptr>";
6218 }
6219 return connection->getInputChannelName();
6220}
6221
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006222void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006223 mAnrTracker.eraseToken(connection->getToken());
6224 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006225}
6226
Prabir Pradhancef936d2021-07-21 16:17:52 +00006227void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006228 const std::shared_ptr<Connection>& connection,
6229 uint32_t seq, bool handled,
6230 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006232 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006233
6234 { // Start critical section
6235 auto dispatchEntryIt =
6236 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6237 [seq](auto& e) { return e->seq == seq; });
6238 if (dispatchEntryIt == connection->waitQueue.end()) {
6239 return;
6240 }
6241
6242 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6243
6244 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6245 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006246 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006247 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6248 }
6249 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006250 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006251 dispatchEntry.deliveryTime, consumeTime, finishTime);
6252 }
6253
6254 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006255 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6256 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006257 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006258 }
6259 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006260
6261 // Dequeue the event and start the next cycle.
6262 // Because the lock might have been released, it is possible that the
6263 // contents of the wait queue to have been drained, so we need to double-check
6264 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006265 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6266 [seq](auto& e) { return e->seq == seq; });
6267 if (entryIt != connection->waitQueue.end()) {
6268 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6269 connection->waitQueue.erase(entryIt);
6270
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006271 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006272 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6273 if (!connection->responsive) {
6274 connection->responsive = isConnectionResponsive(*connection);
6275 if (connection->responsive) {
6276 // The connection was unresponsive, and now it's responsive.
6277 processConnectionResponsiveLocked(*connection);
6278 }
6279 }
6280 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006281 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006282 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6283 // Only dispatch fallbacks if there is a window for the connection.
6284 if (windowHandle != nullptr) {
6285 const auto inputTarget =
6286 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6287 dispatchEntry->targetFlags,
6288 fallbackKeyEntry->downTime);
6289 if (inputTarget.has_value()) {
6290 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6291 *inputTarget);
6292 }
6293 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006294 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006295 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006296 }
6297
6298 // Start the next dispatch cycle for this connection.
6299 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300}
6301
Prabir Pradhancef936d2021-07-21 16:17:52 +00006302void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6303 const sp<IBinder>& newToken) {
6304 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6305 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006306 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 };
6308 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309}
6310
Prabir Pradhancef936d2021-07-21 16:17:52 +00006311void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6312 auto command = [this, token, x, y]() REQUIRES(mLock) {
6313 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006314 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315 };
6316 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006317}
6318
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006319void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006320 if (connection == nullptr) {
6321 LOG_ALWAYS_FATAL("Caller must check for nullness");
6322 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006323 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6324 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006325 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006326 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006327 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006328 return;
6329 }
6330 /**
6331 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6332 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6333 * has changed. This could cause newer entries to time out before the already dispatched
6334 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6335 * processes the events linearly. So providing information about the oldest entry seems to be
6336 * most useful.
6337 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006338 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6339 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006340 std::string reason =
6341 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006342 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006343 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006344 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006345 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006346 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006347
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006348 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6349
6350 // Stop waking up for events on this connection, it is already unresponsive
6351 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006352}
6353
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006354void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6355 std::string reason =
6356 StringPrintf("%s does not have a focused window", application->getName().c_str());
6357 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006358
Yabin Cui8eb9c552023-06-08 18:05:07 +00006359 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006360 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006361 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006362 };
6363 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006364}
6365
chaviw98318de2021-05-19 16:45:23 -05006366void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006367 const std::string& reason) {
6368 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6369 updateLastAnrStateLocked(windowLabel, reason);
6370}
6371
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006372void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6373 const std::string& reason) {
6374 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006375 updateLastAnrStateLocked(windowLabel, reason);
6376}
6377
6378void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6379 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006381 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006382 struct tm tm;
6383 localtime_r(&t, &tm);
6384 char timestr[64];
6385 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006386 mLastAnrState.clear();
6387 mLastAnrState += INDENT "ANR:\n";
6388 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006389 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6390 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006391 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392}
6393
Prabir Pradhancef936d2021-07-21 16:17:52 +00006394void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006395 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006396 const KeyEvent event = createKeyEvent(entry);
6397 nsecs_t delay = 0;
6398 { // release lock
6399 scoped_unlock unlock(mLock);
6400 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006401 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006402 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6403 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6404 std::to_string(t.duration().count()).c_str());
6405 }
6406 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407
6408 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006409 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006410 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006411 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006413 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006414 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416}
6417
Prabir Pradhancef936d2021-07-21 16:17:52 +00006418void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006419 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006420 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006421 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006422 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006423 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006424 };
6425 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006426}
6427
Prabir Pradhanedd96402022-02-15 01:46:16 -08006428void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006429 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006430 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006431 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006432 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006433 };
6434 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006435}
6436
6437/**
6438 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6439 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6440 * command entry to the command queue.
6441 */
6442void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6443 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006444 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006445 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006446 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006447 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006449 pid = findMonitorPidByTokenLocked(connectionToken);
6450 } else {
6451 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006452 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006453 reason.c_str());
6454 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6455 if (handle != nullptr) {
6456 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006457 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006458 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006459 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006460}
6461
6462/**
6463 * Tell the policy that a connection has become responsive so that it can stop ANR.
6464 */
6465void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006466 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006467 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006468 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006469 pid = findMonitorPidByTokenLocked(connectionToken);
6470 } else {
6471 // The connection is a window
6472 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6473 if (handle != nullptr) {
6474 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006475 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006476 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006477 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006478}
6479
Prabir Pradhan24047542023-11-02 17:14:59 +00006480std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006481 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006482 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006483 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006484 if (!handled) {
6485 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006486 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006487 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006488 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006490
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006491 // Get the fallback key state.
6492 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006493 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006494 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006495 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006496 connection->inputState.removeFallbackKey(originalKeyCode);
6497 }
6498
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006499 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500 // If the application handles the original key for which we previously
6501 // generated a fallback or if the window is not a foreground window,
6502 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006503 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006504 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006505 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6506 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6507 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6508 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6509 keyEntry.policyFlags);
6510 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006511 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513
6514 mLock.unlock();
6515
Prabir Pradhana41d2442023-04-20 21:30:40 +00006516 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006517 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6518 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006519 unhandledKeyFallback) {
6520 event = *unhandledKeyFallback;
6521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522
6523 mLock.lock();
6524
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006525 // Cancel the fallback key, but only if we still have a window for the channel.
6526 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006527 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006528 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6529 if (windowHandle != nullptr) {
6530 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6531 "application handled the original non-fallback key "
6532 "or is no longer a foreground target, "
6533 "canceling previously dispatched fallback key");
6534 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006535 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 connection->inputState.removeFallbackKey(originalKeyCode);
6539 }
6540 } else {
6541 // If the application did not handle a non-fallback key, first check
6542 // that we are in a good state to perform unhandled key event processing
6543 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006544 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006545 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006546 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6547 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6548 "since this is not an initial down. "
6549 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6550 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6551 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006552 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006555 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006556 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6557 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6558 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6559 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6560 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006561 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006562
6563 mLock.unlock();
6564
Prabir Pradhana41d2442023-04-20 21:30:40 +00006565 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006566 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6567 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006568 fb) {
6569 fallback = true;
6570 event = *fb;
6571 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006572
6573 mLock.lock();
6574
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006575 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006576 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006577 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006578 }
6579
6580 // Latch the fallback keycode for this key on an initial down.
6581 // The fallback keycode cannot change at any other point in the lifecycle.
6582 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006583 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006584 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006585 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006586 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006587 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006588 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006589 }
6590
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006591 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006592
6593 // Cancel the fallback key if the policy decides not to send it anymore.
6594 // We will continue to dispatch the key to the policy but we will no
6595 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006596 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6597 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006598 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6599 if (fallback) {
6600 ALOGD("Unhandled key event: Policy requested to send key %d"
6601 "as a fallback for %d, but on the DOWN it had requested "
6602 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006603 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006604 } else {
6605 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6606 "but on the DOWN it had requested to send %d. "
6607 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006608 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006609 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006611
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006612 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6613 if (windowHandle != nullptr) {
6614 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6615 "canceling fallback, policy no longer desires it");
6616 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006617 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006618 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006619
6620 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006621 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006622 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006623 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006624 }
6625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006626
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006627 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6628 {
6629 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006630 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006631 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006632 for (const auto& [key, value] : fallbackKeys) {
6633 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006634 }
6635 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6636 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006638 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006639
6640 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006641 // Return the fallback key that we want dispatched to the channel.
6642 std::unique_ptr<KeyEntry> newEntry =
6643 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6644 event.getEventTime(), event.getDeviceId(),
6645 event.getSource(), event.getDisplayId(),
6646 keyEntry.policyFlags, keyEntry.action,
6647 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6648 *fallbackKeyCode, event.getScanCode(),
6649 event.getMetaState(), event.getRepeatCount(),
6650 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006651 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6652 ALOGD("Unhandled key event: Dispatching fallback key. "
6653 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006654 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006655 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006656 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006657 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006658 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6659 ALOGD("Unhandled key event: No fallback key.");
6660 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006661
6662 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006663 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006664 }
6665 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006666 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006667}
6668
Michael Wrightd02c5b62014-02-10 15:10:22 -08006669void InputDispatcher::traceInboundQueueLengthLocked() {
6670 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006671 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 }
6673}
6674
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006675void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006676 if (ATRACE_ENABLED()) {
6677 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006678 snprintf(counterName, sizeof(counterName), "oq:%s",
6679 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006680 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681 }
6682}
6683
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006684void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006685 if (ATRACE_ENABLED()) {
6686 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006687 snprintf(counterName, sizeof(counterName), "wq:%s",
6688 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006689 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690 }
6691}
6692
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006693void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006694 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006695
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006696 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006697 dumpDispatchStateLocked(dump);
6698
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006699 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006700 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006701 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 }
6703}
6704
6705void InputDispatcher::monitor() {
6706 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006707 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006708 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006709 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006710}
6711
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006712/**
6713 * Wake up the dispatcher and wait until it processes all events and commands.
6714 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6715 * this method can be safely called from any thread, as long as you've ensured that
6716 * the work you are interested in completing has already been queued.
6717 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006718bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006719 /**
6720 * Timeout should represent the longest possible time that a device might spend processing
6721 * events and commands.
6722 */
6723 constexpr std::chrono::duration TIMEOUT = 100ms;
6724 std::unique_lock lock(mLock);
6725 mLooper->wake();
6726 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6727 return result == std::cv_status::no_timeout;
6728}
6729
Vishnu Naire798b472020-07-23 13:52:21 -07006730/**
6731 * Sets focus to the window identified by the token. This must be called
6732 * after updating any input window handles.
6733 *
6734 * Params:
6735 * request.token - input channel token used to identify the window that should gain focus.
6736 * request.focusedToken - the token that the caller expects currently to be focused. If the
6737 * specified token does not match the currently focused window, this request will be dropped.
6738 * If the specified focused token matches the currently focused window, the call will succeed.
6739 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6740 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6741 * when requesting the focus change. This determines which request gets
6742 * precedence if there is a focus change request from another source such as pointer down.
6743 */
Vishnu Nair958da932020-08-21 17:12:37 -07006744void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6745 { // acquire lock
6746 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006747 std::optional<FocusResolver::FocusChanges> changes =
6748 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6749 if (changes) {
6750 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006751 }
6752 } // release lock
6753 // Wake up poll loop since it may need to make new input dispatching choices.
6754 mLooper->wake();
6755}
6756
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006757void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6758 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006759 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006760 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6761 ? removedFocusedWindowHandle
6762 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6763 if (resolvedWindow == nullptr) {
6764 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006765 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006766 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6767 "focus left window");
6768 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6769 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006770 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006771 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006772 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006773 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006774 }
6775
Prabir Pradhan99987712020-11-10 18:43:05 -08006776 // If a window has pointer capture, then it must have focus. We need to ensure that this
6777 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6778 // If the window loses focus before it loses pointer capture, then the window can be in a state
6779 // where it has pointer capture but not focus, violating the contract. Therefore we must
6780 // dispatch the pointer capture event before the focus event. Since focus events are added to
6781 // the front of the queue (above), we add the pointer capture event to the front of the queue
6782 // after the focus events are added. This ensures the pointer capture event ends up at the
6783 // front.
6784 disablePointerCaptureForcedLocked();
6785
Vishnu Nairc519ff72021-01-21 08:23:08 -08006786 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006787 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006788 }
6789}
Vishnu Nair958da932020-08-21 17:12:37 -07006790
Prabir Pradhan99987712020-11-10 18:43:05 -08006791void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006792 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006793 return;
6794 }
6795
6796 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6797
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006798 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006799 setPointerCaptureLocked(false);
6800 }
6801
6802 if (!mWindowTokenWithPointerCapture) {
6803 // No need to send capture changes because no window has capture.
6804 return;
6805 }
6806
6807 if (mPendingEvent != nullptr) {
6808 // Move the pending event to the front of the queue. This will give the chance
6809 // for the pending event to be dropped if it is a captured event.
6810 mInboundQueue.push_front(mPendingEvent);
6811 mPendingEvent = nullptr;
6812 }
6813
6814 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006815 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006816 mInboundQueue.push_front(std::move(entry));
6817}
6818
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006819void InputDispatcher::setPointerCaptureLocked(bool enable) {
6820 mCurrentPointerCaptureRequest.enable = enable;
6821 mCurrentPointerCaptureRequest.seq++;
6822 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006823 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006824 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006825 };
6826 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006827}
6828
Vishnu Nair599f1412021-06-21 10:39:58 -07006829void InputDispatcher::displayRemoved(int32_t displayId) {
6830 { // acquire lock
6831 std::scoped_lock _l(mLock);
6832 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006833 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006834 setFocusedApplicationLocked(displayId, nullptr);
6835 // Call focus resolver to clean up stale requests. This must be called after input windows
6836 // have been removed for the removed display.
6837 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006838 // Reset pointer capture eligibility, regardless of previous state.
6839 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006840 // Remove the associated touch mode state.
6841 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006842 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006843 } // release lock
6844
6845 // Wake up poll loop since it may need to make new input dispatching choices.
6846 mLooper->wake();
6847}
6848
Patrick Williamsd828f302023-04-28 17:52:08 -05006849void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006850 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6851 {
6852 // acquire lock
6853 std::scoped_lock _l(mLock);
6854 logDispatchStateLocked();
6855 }
6856 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6857 result.error().message().c_str());
6858 };
chaviw15fab6f2021-06-07 14:15:52 -05006859 // The listener sends the windows as a flattened array. Separate the windows by display for
6860 // more convenient parsing.
6861 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006862 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006863 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006864 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006865 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006866
6867 { // acquire lock
6868 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006869
6870 // Ensure that we have an entry created for all existing displays so that if a displayId has
6871 // no windows, we can tell that the windows were removed from the display.
6872 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6873 handlesPerDisplay[displayId];
6874 }
6875
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006876 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006877 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006878 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6879 }
6880
6881 for (const auto& [displayId, handles] : handlesPerDisplay) {
6882 setInputWindowsLocked(handles, displayId);
6883 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006884
6885 if (update.vsyncId < mWindowInfosVsyncId) {
6886 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6887 ", current update vsync id: %" PRId64,
6888 mWindowInfosVsyncId, update.vsyncId);
6889 }
6890 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006891 }
6892 // Wake up poll loop since it may need to make new input dispatching choices.
6893 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006894}
6895
Vishnu Nair062a8672021-09-03 16:07:44 -07006896bool InputDispatcher::shouldDropInput(
6897 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006898 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6899 (windowHandle->getInfo()->inputConfig.test(
6900 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006901 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006902 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6903 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006904 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006905 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006906 windowHandle->getInfo()->displayId);
6907 return true;
6908 }
6909 return false;
6910}
6911
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006912void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006913 const gui::WindowInfosUpdate& update) {
6914 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006915}
6916
Arthur Hungdfd528e2021-12-08 13:23:04 +00006917void InputDispatcher::cancelCurrentTouch() {
6918 {
6919 std::scoped_lock _l(mLock);
6920 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006921 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006922 "cancel current touch");
6923 synthesizeCancelationEventsForAllConnectionsLocked(options);
6924
6925 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006926 }
6927 // Wake up poll loop since there might be work to do.
6928 mLooper->wake();
6929}
6930
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006931void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6932 std::scoped_lock _l(mLock);
6933 mMonitorDispatchingTimeout = timeout;
6934}
6935
Arthur Hungc539dbb2022-12-08 07:45:36 +00006936void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6937 const sp<WindowInfoHandle>& oldWindowHandle,
6938 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006939 TouchState& state, int32_t deviceId,
6940 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006941 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006942 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006943 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6944 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6945 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6946 newWindowHandle->getInfo()->inputConfig.test(
6947 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6948 const sp<WindowInfoHandle> oldWallpaper =
6949 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6950 const sp<WindowInfoHandle> newWallpaper =
6951 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6952 if (oldWallpaper == newWallpaper) {
6953 return;
6954 }
6955
6956 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006957 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006958 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006959 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006960 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006961 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006962 }
6963
6964 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006965 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6966 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006967 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006968 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 }
6970}
6971
6972void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6973 ftl::Flags<InputTarget::Flags> newTargetFlags,
6974 const sp<WindowInfoHandle> fromWindowHandle,
6975 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006976 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006977 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006978 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6979 fromWindowHandle->getInfo()->inputConfig.test(
6980 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6981 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6982 toWindowHandle->getInfo()->inputConfig.test(
6983 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6984
6985 const sp<WindowInfoHandle> oldWallpaper =
6986 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6987 const sp<WindowInfoHandle> newWallpaper =
6988 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6989 if (oldWallpaper == newWallpaper) {
6990 return;
6991 }
6992
6993 if (oldWallpaper != nullptr) {
6994 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6995 "transferring touch focus to another window");
6996 state.removeWindowByToken(oldWallpaper->getToken());
6997 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6998 }
6999
7000 if (newWallpaper != nullptr) {
7001 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007002 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7003 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007004 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7005 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007006 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007007 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007008 std::shared_ptr<Connection> wallpaperConnection =
7009 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007010 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007011 std::shared_ptr<Connection> toConnection =
7012 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007013 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7014 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7015 wallpaperFlags);
7016 }
7017 }
7018}
7019
7020sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7021 const sp<WindowInfoHandle>& windowHandle) const {
7022 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7023 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7024 bool foundWindow = false;
7025 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7026 if (!foundWindow && otherHandle != windowHandle) {
7027 continue;
7028 }
7029 if (windowHandle == otherHandle) {
7030 foundWindow = true;
7031 continue;
7032 }
7033
7034 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7035 return otherHandle;
7036 }
7037 }
7038 return nullptr;
7039}
7040
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007041void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7042 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007043 std::scoped_lock _l(mLock);
7044
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007045 mConfig.keyRepeatTimeout = timeout.count();
7046 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007047}
7048
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007049bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7050 DeviceId deviceId, int32_t pointerId) {
7051 std::scoped_lock _l(mLock);
7052 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7053 if (touchStateIt == mTouchStatesByDisplay.end()) {
7054 return false;
7055 }
7056 for (const TouchedWindow& window : touchStateIt->second.windows) {
7057 if (window.windowHandle->getToken() == token &&
7058 (window.hasTouchingPointer(deviceId, pointerId) ||
7059 window.hasHoveringPointer(deviceId, pointerId))) {
7060 return true;
7061 }
7062 }
7063 return false;
7064}
7065
Garfield Tane84e6f92019-08-29 17:28:41 -07007066} // namespace android::inputdispatcher