blob: 71afbccfab64bbae489c885fd4851f3c97952980 [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();
1315 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001318 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001319 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1320 break;
1321 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001322 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001323 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001324 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001325 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001326 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1327 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001328 // nothing to do
1329 break;
1330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
1332
1333 return needWake;
1334}
1335
Prabir Pradhan24047542023-11-02 17:14:59 +00001336void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001337 // Do not store sensor event in recent queue to avoid flooding the queue.
1338 if (entry->type != EventEntry::Type::SENSOR) {
1339 mRecentQueue.push_back(entry);
1340 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001341 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001342 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344}
1345
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001346sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1347 bool isStylus,
1348 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001350 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001351 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001352 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001353 continue;
1354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001356 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001357 if (!info.isSpy() &&
1358 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001359 return windowHandle;
1360 }
1361 }
1362 return nullptr;
1363}
1364
1365std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001366 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001367 if (touchedWindow == nullptr) {
1368 return {};
1369 }
1370 // Traverse windows from front to back until we encounter the touched window.
1371 std::vector<InputTarget> outsideTargets;
1372 const auto& windowHandles = getWindowHandlesLocked(displayId);
1373 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1374 if (windowHandle == touchedWindow) {
1375 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1376 // below the touched window will not get ACTION_OUTSIDE event.
1377 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001378 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001379
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001380 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001381 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001382 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1383 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001384 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1385 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001386 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 }
1388 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001389 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390}
1391
Prabir Pradhand65552b2021-10-07 11:23:50 -07001392std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001393 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001394 // Traverse windows from front to back and gather the touched spy windows.
1395 std::vector<sp<WindowInfoHandle>> spyWindows;
1396 const auto& windowHandles = getWindowHandlesLocked(displayId);
1397 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1398 const WindowInfo& info = *windowHandle->getInfo();
1399
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001400 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001401 continue;
1402 }
1403 if (!info.isSpy()) {
1404 // The first touched non-spy window was found, so return the spy windows touched so far.
1405 return spyWindows;
1406 }
1407 spyWindows.push_back(windowHandle);
1408 }
1409 return spyWindows;
1410}
1411
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001412void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 const char* reason;
1414 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001415 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001416 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001417 ALOGD("Dropped event because policy consumed it.");
1418 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 reason = "inbound event was dropped because the policy consumed it";
1420 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001421 case DropReason::DISABLED:
1422 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 ALOGI("Dropped event because input dispatch is disabled.");
1424 }
1425 reason = "inbound event was dropped because input dispatch is disabled";
1426 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001427 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001428 LOG(INFO) << "Dropping because the current application is not responding and the user "
1429 "has started interacting with a different application: "
1430 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 reason = "inbound event was dropped because the current application is not responding "
1432 "and the user has started interacting with a different application";
1433 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001434 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 ALOGI("Dropped event because it is stale.");
1436 reason = "inbound event was dropped because it is stale";
1437 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001438 case DropReason::NO_POINTER_CAPTURE:
1439 ALOGI("Dropped event because there is no window with Pointer Capture.");
1440 reason = "inbound event was dropped because there is no window with Pointer Capture";
1441 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001442 case DropReason::NOT_DROPPED: {
1443 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 }
1447
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001449 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001450 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001451 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1452 options.displayId = keyEntry.displayId;
1453 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001457 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001458 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1459 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001460 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001461 options.displayId = motionEntry.displayId;
1462 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001463 synthesizeCancelationEventsForAllConnectionsLocked(options);
1464 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001465 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1466 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001467 options.displayId = motionEntry.displayId;
1468 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001469 synthesizeCancelationEventsForAllConnectionsLocked(options);
1470 }
1471 break;
1472 }
Chris Yef59a2f42020-10-16 12:55:26 -07001473 case EventEntry::Type::SENSOR: {
1474 break;
1475 }
arthurhungb89ccb02020-12-30 16:19:01 +08001476 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1477 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001478 break;
1479 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001480 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001481 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001482 case EventEntry::Type::CONFIGURATION_CHANGED:
1483 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001484 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001485 break;
1486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488}
1489
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001491 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492}
1493
Prabir Pradhancef936d2021-07-21 16:17:52 +00001494bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001495 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 return false;
1497 }
1498
1499 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001500 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001501 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001502 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1503 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001504 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return true;
1506}
1507
Prabir Pradhancef936d2021-07-21 16:17:52 +00001508void InputDispatcher::postCommandLocked(Command&& command) {
1509 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510}
1511
1512void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001513 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001514 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001515 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 releaseInboundEventLocked(entry);
1517 }
1518 traceInboundQueueLengthLocked();
1519}
1520
1521void InputDispatcher::releasePendingEventLocked() {
1522 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001524 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526}
1527
Prabir Pradhan24047542023-11-02 17:14:59 +00001528void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001529 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001531 if (DEBUG_DISPATCH_CYCLE) {
1532 ALOGD("Injected inbound event was dropped.");
1533 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001534 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 }
1536 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001537 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 }
1539 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540}
1541
1542void InputDispatcher::resetKeyRepeatLocked() {
1543 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001544 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546}
1547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001549 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550
Michael Wright2e732952014-09-24 13:26:59 -07001551 uint32_t policyFlags = entry->policyFlags &
1552 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001555 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1556 currentTime, entry->deviceId, entry->source,
1557 entry->displayId, policyFlags, entry->action, entry->flags,
1558 entry->keyCode, entry->scanCode, entry->metaState,
1559 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001562 if (mTracer) {
1563 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1564 }
1565
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001566 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569}
1570
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001572 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001573 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1574 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576
1577 // Reset key repeating in case a keyboard device was added or removed or something.
1578 resetKeyRepeatLocked();
1579
1580 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001581 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1582 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001583 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001584 };
1585 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return true;
1587}
1588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1590 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001591 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1592 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1593 entry.deviceId);
1594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595
liushenxiang42232912021-05-21 20:24:09 +08001596 // Reset key repeating in case a keyboard device was disabled or enabled.
1597 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1598 resetKeyRepeatLocked();
1599 }
1600
Michael Wrightfb04fd52022-11-24 22:31:11 +00001601 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001602 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001604
1605 // Remove all active pointers from this device
1606 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1607 touchState.removeAllPointersForDevice(entry.deviceId);
1608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 return true;
1610}
1611
Vishnu Nairad321cd2020-08-20 16:40:21 -07001612void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001613 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001614 if (mPendingEvent != nullptr) {
1615 // Move the pending event to the front of the queue. This will give the chance
1616 // for the pending event to get dispatched to the newly focused window
1617 mInboundQueue.push_front(mPendingEvent);
1618 mPendingEvent = nullptr;
1619 }
1620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621 std::unique_ptr<FocusEntry> focusEntry =
1622 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1623 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001624
1625 // This event should go to the front of the queue, but behind all other focus events
1626 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001627 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1628 [](const std::shared_ptr<const EventEntry>& event) {
1629 return event->type == EventEntry::Type::FOCUS;
1630 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001631
1632 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001633 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001634}
1635
Prabir Pradhan24047542023-11-02 17:14:59 +00001636void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1637 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001638 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1639 if (connection == nullptr) {
1640 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001641 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001642 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001643 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001644 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001645 std::string reason = std::string("reason=").append(entry->reason);
1646 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001647 dispatchEventLocked(currentTime, entry, {{connection}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001648}
1649
Prabir Pradhan99987712020-11-10 18:43:05 -08001650void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001651 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001652 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001653 dropReason = DropReason::NOT_DROPPED;
1654
Prabir Pradhan99987712020-11-10 18:43:05 -08001655 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001656 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001657
1658 if (entry->pointerCaptureRequest.enable) {
1659 // Enable Pointer Capture.
1660 if (haveWindowWithPointerCapture &&
1661 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001662 // This can happen if pointer capture is disabled and re-enabled before we notify the
1663 // app of the state change, so there is no need to notify the app.
1664 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1665 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001666 }
1667 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001668 // This can happen if a window requests capture and immediately releases capture.
1669 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001670 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001671 return;
1672 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001673 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1674 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1675 return;
1676 }
1677
Vishnu Nairc519ff72021-01-21 08:23:08 -08001678 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001679 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1680 mWindowTokenWithPointerCapture = token;
1681 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001682 // Disable Pointer Capture.
1683 // We do not check if the sequence number matches for requests to disable Pointer Capture
1684 // for two reasons:
1685 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1686 // to disable capture with the same sequence number: one generated by
1687 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1688 // Capture being disabled in InputReader.
1689 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1690 // actual Pointer Capture state that affects events being generated by input devices is
1691 // in InputReader.
1692 if (!haveWindowWithPointerCapture) {
1693 // Pointer capture was already forcefully disabled because of focus change.
1694 dropReason = DropReason::NOT_DROPPED;
1695 return;
1696 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001697 token = mWindowTokenWithPointerCapture;
1698 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001699 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001700 setPointerCaptureLocked(false);
1701 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001702 }
1703
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001704 auto connection = getConnectionLocked(token);
1705 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001706 // Window has gone away, clean up Pointer Capture state.
1707 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001708 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001709 setPointerCaptureLocked(false);
1710 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001711 return;
1712 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001713 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001714 dispatchEventLocked(currentTime, entry, {{connection}});
Prabir Pradhan99987712020-11-10 18:43:05 -08001715
1716 dropReason = DropReason::NOT_DROPPED;
1717}
1718
Prabir Pradhan24047542023-11-02 17:14:59 +00001719void InputDispatcher::dispatchTouchModeChangeLocked(
1720 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001721 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001722 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001723 if (windowHandles.empty()) {
1724 return;
1725 }
1726 const std::vector<InputTarget> inputTargets =
1727 getInputTargetsFromWindowHandlesLocked(windowHandles);
1728 if (inputTargets.empty()) {
1729 return;
1730 }
1731 entry->dispatchInProgress = true;
1732 dispatchEventLocked(currentTime, entry, inputTargets);
1733}
1734
1735std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1736 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1737 std::vector<InputTarget> inputTargets;
1738 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001739 const sp<IBinder>& token = handle->getToken();
1740 if (token == nullptr) {
1741 continue;
1742 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001743 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1744 if (connection == nullptr) {
1745 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001746 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00001747 inputTargets.emplace_back(connection);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001748 }
1749 return inputTargets;
1750}
1751
Prabir Pradhan24047542023-11-02 17:14:59 +00001752bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001753 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 if (!entry->dispatchInProgress) {
1756 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1757 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1758 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1759 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001760 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 // We have seen two identical key downs in a row which indicates that the device
1762 // driver is automatically generating key repeats itself. We take note of the
1763 // repeat here, but we disable our own next key repeat timer since it is clear that
1764 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001765 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1766 // Make sure we don't get key down from a different device. If a different
1767 // device Id has same key pressed down, the new device Id will replace the
1768 // current one to hold the key repeat with repeat count reset.
1769 // In the future when got a KEY_UP on the device id, drop it and do not
1770 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1772 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001773 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 } else {
1775 // Not a repeat. Save key down state in case we do see a repeat later.
1776 resetKeyRepeatLocked();
1777 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1778 }
1779 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001780 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1781 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001782 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001783 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001784 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1785 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 resetKeyRepeatLocked();
1788 }
1789
1790 if (entry->repeatCount == 1) {
1791 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1792 } else {
1793 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1794 }
1795
1796 entry->dispatchInProgress = true;
1797
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001798 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800
1801 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001802 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001804 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 return false; // wait until next wakeup
1806 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001807 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 entry->interceptKeyWakeupTime = 0;
1809 }
1810
1811 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001812 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001814 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001815 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001816
1817 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1818 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1819 };
1820 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001821 // Poke user activity for keys not passed to user
1822 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 return false; // wait for the command to run
1824 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001825 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001827 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001828 if (*dropReason == DropReason::NOT_DROPPED) {
1829 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 }
1831 }
1832
1833 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001834 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001835 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1837 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001838 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001839 // Poke user activity for undispatched keys
1840 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 return true;
1842 }
1843
1844 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001845 InputEventInjectionResult injectionResult;
1846 sp<WindowInfoHandle> focusedWindow =
1847 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1848 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001849 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 return false;
1851 }
1852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001853 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001854 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 return true;
1856 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001857 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1858
1859 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001860 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1861 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001863 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001864 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001866 if (mTracer) {
1867 ensureEventTraced(*entry);
1868 for (const auto& target : inputTargets) {
1869 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1870 }
1871 }
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 // Dispatch the key.
1874 dispatchEventLocked(currentTime, entry, inputTargets);
1875 return true;
1876}
1877
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001878void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001879 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1880 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1881 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1882 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1883 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1884 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1885 entry.metaState, entry.repeatCount, entry.downTime);
1886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887}
1888
Prabir Pradhancef936d2021-07-21 16:17:52 +00001889void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001890 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001891 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001892 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1893 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1894 "source=0x%x, sensorType=%s",
1895 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001896 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001897 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001898 auto command = [this, entry]() REQUIRES(mLock) {
1899 scoped_unlock unlock(mLock);
1900
1901 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001902 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001903 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001904 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1905 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001906 };
1907 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001908}
1909
1910bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001911 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1912 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001913 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001914 }
Chris Yef59a2f42020-10-16 12:55:26 -07001915 { // acquire lock
1916 std::scoped_lock _l(mLock);
1917
1918 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001919 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001920 if (entry->type == EventEntry::Type::SENSOR) {
1921 it = mInboundQueue.erase(it);
1922 releaseInboundEventLocked(entry);
1923 }
1924 }
1925 }
1926 return true;
1927}
1928
Prabir Pradhan24047542023-11-02 17:14:59 +00001929bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1930 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001931 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001932 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001934 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 entry->dispatchInProgress = true;
1936
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001937 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 }
1939
1940 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001941 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001942 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1944 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 return true;
1946 }
1947
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001948 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949
1950 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001951 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001953 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 if (isPointerEvent) {
1955 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001956
1957 if (mDragState &&
1958 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1959 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1960 pilferPointersLocked(mDragState->dragWindow->getToken());
1961 }
1962
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001963 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001964 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001965 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1966 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 } else {
1968 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001969 sp<WindowInfoHandle> focusedWindow =
1970 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1971 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1972 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001973 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1974 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1975 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001978 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 return false;
1980 }
1981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001982 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001983 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 return true;
1985 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001987 CancelationOptions::Mode mode(
1988 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1989 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001991 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 return true;
1994 }
1995
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001996 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001997 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001999 if (mTracer) {
2000 ensureEventTraced(*entry);
2001 for (const auto& target : inputTargets) {
2002 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
2003 }
2004 }
2005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 dispatchEventLocked(currentTime, entry, inputTargets);
2008 return true;
2009}
2010
chaviw98318de2021-05-19 16:45:23 -05002011void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002012 bool isExiting, const int32_t rawX,
2013 const int32_t rawY) {
2014 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002015 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002016 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2017 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002018
2019 enqueueInboundEventLocked(std::move(dragEntry));
2020}
2021
Prabir Pradhan24047542023-11-02 17:14:59 +00002022void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2023 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002024 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2025 if (connection == nullptr) {
2026 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002027 }
arthurhungb89ccb02020-12-30 16:19:01 +08002028 entry->dispatchInProgress = true;
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002029 dispatchEventLocked(currentTime, entry, {{connection}});
arthurhungb89ccb02020-12-30 16:19:01 +08002030}
2031
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002033 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002034 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002035 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002036 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002037 "metaState=0x%x, buttonState=0x%x,"
2038 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002039 prefix, entry.eventTime, entry.deviceId,
2040 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2041 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2042 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2043 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002045 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002046 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002047 "x=%f, y=%f, pressure=%f, size=%f, "
2048 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2049 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002050 i, entry.pointerProperties[i].id,
2051 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002052 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2053 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2054 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2055 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2056 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2057 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2058 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2059 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2060 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063}
2064
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002065void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002066 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002067 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002068 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002069 if (DEBUG_DISPATCH_CYCLE) {
2070 ALOGD("dispatchEventToCurrentInputTargets");
2071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002073 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002074
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2076
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002077 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002079 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002080 std::shared_ptr<Connection> connection = inputTarget.connection;
2081 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
2083}
2084
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002085void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2087 // If the policy decides to close the app, we will get a channel removal event via
2088 // unregisterInputChannel, and will clean up the connection that way. We are already not
2089 // sending new pointers to the connection when it blocked, but focused events will continue to
2090 // pile up.
2091 ALOGW("Canceling events for %s because it is unresponsive",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002092 connection->getInputChannelName().c_str());
Prabir Pradhanfc364722024-02-08 17:51:20 +00002093 if (connection->status != Connection::Status::NORMAL) {
2094 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
Prabir Pradhanfc364722024-02-08 17:51:20 +00002096 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
2097 "application not responding");
2098
2099 sp<WindowInfoHandle> windowHandle;
2100 if (!connection->monitor) {
2101 windowHandle = getWindowHandleLocked(connection->getToken());
2102 if (windowHandle == nullptr) {
2103 // The window that is receiving this ANR was removed, so there is no need to generate
2104 // cancellations, because the cancellations would have already been generated when
2105 // the window was removed.
2106 return;
2107 }
2108 }
2109 synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110}
2111
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002113 if (DEBUG_FOCUS) {
2114 ALOGD("Resetting ANR timeouts.");
2115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116
2117 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002119 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120}
2121
Tiger Huang721e26f2018-07-24 22:26:19 +08002122/**
2123 * Get the display id that the given event should go to. If this event specifies a valid display id,
2124 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2125 * Focused display is the display that the user most recently interacted with.
2126 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002127int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002128 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002129 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002130 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002131 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2132 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002133 break;
2134 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002135 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002136 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2137 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 break;
2139 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002140 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002141 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002142 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002143 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002144 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002145 case EventEntry::Type::SENSOR:
2146 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002147 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148 return ADISPLAY_ID_NONE;
2149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002150 }
2151 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2152}
2153
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002154bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2155 const char* focusedWindowName) {
2156 if (mAnrTracker.empty()) {
2157 // already processed all events that we waited for
2158 mKeyIsWaitingForEventsTimeout = std::nullopt;
2159 return false;
2160 }
2161
2162 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2163 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002164 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002165 mKeyIsWaitingForEventsTimeout = currentTime +
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08002166 std::chrono::duration_cast<std::chrono::nanoseconds>(
2167 mPolicy.getKeyWaitingForEventsTimeout())
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002168 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002169 return true;
2170 }
2171
2172 // We still have pending events, and already started the timer
2173 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2174 return true; // Still waiting
2175 }
2176
2177 // Waited too long, and some connection still hasn't processed all motions
2178 // Just send the key to the focused window
2179 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2180 focusedWindowName);
2181 mKeyIsWaitingForEventsTimeout = std::nullopt;
2182 return false;
2183}
2184
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002185sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002186 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002187 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189
Tiger Huang721e26f2018-07-24 22:26:19 +08002190 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002191 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002192 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002193 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2194
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 // If there is no currently focused window and no focused application
2196 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002197 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2198 ALOGI("Dropping %s event because there is no focused window or focused application in "
2199 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002200 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002201 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
2203
Vishnu Nair062a8672021-09-03 16:07:44 -07002204 // Drop key events if requested by input feature
2205 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002207 }
2208
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002209 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2210 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2211 // start interacting with another application via touch (app switch). This code can be removed
2212 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2213 // an app is expected to have a focused window.
2214 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2215 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2216 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002217 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2218 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2219 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002220 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002221 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002222 ALOGW("Waiting because no window has focus but %s may eventually add a "
2223 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002224 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002225 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002226 outInjectionResult = InputEventInjectionResult::PENDING;
2227 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002228 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2229 // Already raised ANR. Drop the event
2230 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002231 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002232 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002233 } else {
2234 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::PENDING;
2236 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 }
2238 }
2239
2240 // we have a valid, non-null focused window
2241 resetNoFocusedWindowTimeoutLocked();
2242
Prabir Pradhan5735a322022-04-11 17:23:34 +00002243 // Verify targeted injection.
2244 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2245 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002246 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2247 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 }
2249
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002250 if (focusedWindowHandle->getInfo()->inputConfig.test(
2251 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002252 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = InputEventInjectionResult::PENDING;
2254 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 }
2256
2257 // If the event is a key event, then we must wait for all previous events to
2258 // complete before delivering it because previous events may have the
2259 // side-effect of transferring focus to a different window and we want to
2260 // ensure that the following keys are sent to the new window.
2261 //
2262 // Suppose the user touches a button in a window then immediately presses "A".
2263 // If the button causes a pop-up window to appear then we want to ensure that
2264 // the "A" key is delivered to the new pop-up window. This is because users
2265 // often anticipate pending UI changes when typing on a keyboard.
2266 // To obtain this behavior, we must serialize key events with respect to all
2267 // prior input events.
2268 if (entry.type == EventEntry::Type::KEY) {
2269 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002270 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002271 outInjectionResult = InputEventInjectionResult::PENDING;
2272 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002276 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2277 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278}
2279
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002280/**
2281 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2282 * that are currently unresponsive.
2283 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002284std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2285 const std::vector<Monitor>& monitors) const {
2286 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002287 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002288 [](const Monitor& monitor) REQUIRES(mLock) {
2289 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002290 if (!connection->responsive) {
2291 ALOGW("Unresponsive monitor %s will not get the new gesture",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08002292 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002293 return false;
2294 }
2295 return true;
2296 });
2297 return responsiveMonitors;
2298}
2299
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002300std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002301 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002302 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002305 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 // For security reasons, we defer updating the touch state until we are sure that
2307 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 const int32_t displayId = entry.displayId;
2309 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002310 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311
2312 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002313 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002315 // Copy current touch state into tempTouchState.
2316 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2317 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002318 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002319 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2321 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002322 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002323 }
2324
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002325 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002326
2327 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2328 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2329 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002330 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2331 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002332 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002333 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2334 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002335 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2336 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2337 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002338 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002339
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002340 if (newGesture) {
2341 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002342 }
2343
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002344 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2345 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2346 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
2348
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002349 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002350 if (wasDown) {
2351 // Started hovering, but the device is already down: reject the hover event
2352 LOG(ERROR) << "Got hover event " << entry.getDescription()
2353 << " but the device is already down " << oldState->dump();
2354 outInjectionResult = InputEventInjectionResult::FAILED;
2355 return {};
2356 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002357 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2358 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002359 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002360 }
2361
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2363 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002364 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002365 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002366 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002367 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2368 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002369 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002370 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002371 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002372
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002373 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002374 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002377 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002378 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002380 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002381 }
2382
Prabir Pradhan5735a322022-04-11 17:23:34 +00002383 // Verify targeted injection.
2384 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2385 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002386 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002387 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002388 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002389 }
2390
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002392 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002393 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2394 // New window supports splitting, but we should never split mouse events.
2395 isSplit = !isFromMouse;
2396 } else if (isSplit) {
2397 // New window does not support splitting but we have already split events.
2398 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002399 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2400 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002401 newTouchedWindowHandle = nullptr;
2402 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 } else {
2404 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002405 // be delivered to a new window which supports split touch. Pointers from a mouse device
2406 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002407 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002408 }
2409
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002410 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002411 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002413 // Process the foreground window first so that it is the first to receive the event.
2414 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415 }
2416
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002417 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002418 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2419 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002420 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002421 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002422 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002423 }
2424
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002426 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002427 continue;
2428 }
2429
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002430 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002431 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002432 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002433 }
2434
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002435 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002436 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002437
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002438 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2439 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002440 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002441 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002442
2443 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002444 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002445 }
2446 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002447 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002448 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002450 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002451
2452 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002453
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002454 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002455 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2456 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002457 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002458 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002459 isDownOrPointerDown
2460 ? std::make_optional(entry.eventTime)
2461 : std::nullopt);
2462 // If this is the pointer going down and the touched window has a wallpaper
2463 // then also add the touched wallpaper windows so they are locked in for the
2464 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2465 // SCROLL because the wallpaper engine only supports touch events. We would need to
2466 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2467 // handle these events.
2468 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002469 windowHandle->getInfo()->inputConfig.test(
2470 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2471 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2472 if (wallpaper != nullptr) {
2473 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2474 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002475 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002476 if (isSplit) {
2477 wallpaperFlags |= InputTarget::Flags::SPLIT;
2478 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002479 tempTouchState.addOrUpdateWindow(wallpaper,
2480 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002481 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002482 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002483 }
2484 }
2485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002487
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002488 // If a window is already pilfering some pointers, give it this new pointer as well and
2489 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2490 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002491 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002492 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002493 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002494 // This window is already pilfering some pointers, and this new pointer is also
2495 // going to it. Therefore, take over this pointer and don't give it to anyone
2496 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002497 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002498 }
2499 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002500
2501 // Restrict all pilfered pointers to the pilfering windows.
2502 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 } else {
2504 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2505
2506 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002507 if (!tempTouchState.isDown(entry.deviceId) &&
2508 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002509 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2510 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2511 << " is not down or we previously dropped the pointer down event in "
2512 << "display " << displayId << ": " << entry.getDescription();
2513 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002514 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002515 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002518 // If the pointer is not currently hovering, then ignore the event.
2519 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2520 const int32_t pointerId = entry.pointerProperties[0].id;
2521 if (oldState == nullptr ||
2522 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2523 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2524 "display "
2525 << displayId << ": " << entry.getDescription();
2526 outInjectionResult = InputEventInjectionResult::FAILED;
2527 return {};
2528 }
2529 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2530 }
2531
arthurhung6d4bed92021-03-17 11:59:33 +08002532 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002533
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002535 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002536 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002537 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002538 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002539 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002540 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002541 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002542 sp<WindowInfoHandle> newTouchedWindowHandle =
2543 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002544
Prabir Pradhan5735a322022-04-11 17:23:34 +00002545 // Verify targeted injection.
2546 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2547 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002548 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002549 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002550 }
2551
Vishnu Nair062a8672021-09-03 16:07:44 -07002552 // Drop touch events if requested by input feature
2553 if (newTouchedWindowHandle != nullptr &&
2554 shouldDropInput(entry, newTouchedWindowHandle)) {
2555 newTouchedWindowHandle = nullptr;
2556 }
2557
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002558 if (newTouchedWindowHandle != nullptr &&
2559 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002560 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002561 oldTouchedWindowHandle->getName().c_str(),
2562 newTouchedWindowHandle->getName().c_str(), displayId);
2563
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002565 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002566 const PointerProperties& pointer = entry.pointerProperties[0];
2567 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002568
2569 const TouchedWindow& touchedWindow =
2570 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002571 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002572 InputTarget::DispatchMode::SLIPPERY_EXIT,
2573 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002574 touchedWindow.getDownTimeInTarget(entry.deviceId),
2575 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576
2577 // Make a slippery entrance into the new window.
2578 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002579 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002582 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002583 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002584 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002587 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002590 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002591 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002592 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
2594
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002595 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2596 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002597 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002598 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002599
2600 // Check if the wallpaper window should deliver the corresponding event.
2601 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002602 tempTouchState, entry.deviceId, pointer, targets);
2603 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002604 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 }
2606 }
Arthur Hung96483742022-11-15 03:30:48 +00002607
2608 // Update the pointerIds for non-splittable when it received pointer down.
2609 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2610 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002611 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002612 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2613 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002614 // Ignore drag window for it should just track one pointer.
2615 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2616 continue;
2617 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002618 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002619 }
2620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
2622
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002623 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002624 {
2625 std::vector<TouchedWindow> hoveringWindows =
2626 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2627 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002628 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002629 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2630 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002631 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002632 if (!target) {
2633 continue;
2634 }
2635 // Hardcode to single hovering pointer for now.
2636 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2637 pointerIds.set(entry.pointerProperties[0].id);
2638 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2639 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642
Prabir Pradhan5735a322022-04-11 17:23:34 +00002643 // Ensure that all touched windows are valid for injection.
2644 if (entry.injectionState != nullptr) {
2645 std::string errs;
2646 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002647 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2648 if (err) errs += "\n - " + *err;
2649 }
2650 if (!errs.empty()) {
2651 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002652 "%s:%s",
2653 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002654 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002655 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002656 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002657 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002658
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002659 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2660 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002662 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002663 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002664 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002665 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002666 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002667 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002668 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002669 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002670 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2671 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674 }
2675 }
2676 }
2677
Harry Cuttsb166c002023-05-09 13:06:05 +00002678 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2679 // only want the system UI to handle these gestures.
2680 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2681 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2682 if (isTouchpadNavGesture) {
2683 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2684 }
2685
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002686 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002687 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002688 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002689 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002690 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002691 continue;
2692 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002693 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002694 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002695 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002696 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002697
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002698 // During targeted injection, only allow owned targets to receive events
2699 std::erase_if(targets, [&](const InputTarget& target) {
2700 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2701 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2702 if (err) {
2703 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2704 << ": " << (*err);
2705 return true;
2706 }
2707 return false;
2708 });
2709
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002710 if (targets.empty()) {
2711 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2712 outInjectionResult = InputEventInjectionResult::FAILED;
2713 return {};
2714 }
2715
2716 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2717 // window that is actually receiving the entire gesture.
2718 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002719 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002720 })) {
2721 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2722 << entry.getDescription();
2723 outInjectionResult = InputEventInjectionResult::FAILED;
2724 return {};
2725 }
2726
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002727 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728
Prabir Pradhan502a7252023-12-01 16:11:24 +00002729 // Now that we have generated all of the input targets for this event, reset the dispatch
2730 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002731 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002732 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002733 }
2734
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002735 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002736 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002737 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002738 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002739 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002740 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002741 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002742 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2743 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002744 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2745 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2746 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
2748
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002749 // Save changes unless the action was scroll in which case the temporary touch
2750 // state was only valid for this one action.
2751 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002752 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002753 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002754 mTouchStatesByDisplay[displayId] = tempTouchState;
2755 } else {
2756 mTouchStatesByDisplay.erase(displayId);
2757 }
2758 }
2759
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002760 if (tempTouchState.windows.empty()) {
2761 mTouchStatesByDisplay.erase(displayId);
2762 }
2763
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002764 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765}
2766
arthurhung6d4bed92021-03-17 11:59:33 +08002767void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002768 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2769 // have an explicit reason to support it.
2770 constexpr bool isStylus = false;
2771
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002772 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002773 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002774 if (dropWindow) {
2775 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002776 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002777 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002778 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002779 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002780 }
2781 mDragState.reset();
2782}
2783
2784void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002785 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002786 return;
2787 }
2788
arthurhung6d4bed92021-03-17 11:59:33 +08002789 if (!mDragState->isStartDrag) {
2790 mDragState->isStartDrag = true;
2791 mDragState->isStylusButtonDownAtStart =
2792 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2793 }
2794
Arthur Hung54745652022-04-20 07:17:41 +00002795 // Find the pointer index by id.
2796 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002797 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002798 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2799 if (pointerProperties.id == mDragState->pointerId) {
2800 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002801 }
Arthur Hung54745652022-04-20 07:17:41 +00002802 }
arthurhung6d4bed92021-03-17 11:59:33 +08002803
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002804 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002805 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002806 }
2807
2808 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2809 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2810 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2811
2812 switch (maskedAction) {
2813 case AMOTION_EVENT_ACTION_MOVE: {
2814 // Handle the special case : stylus button no longer pressed.
2815 bool isStylusButtonDown =
2816 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2817 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2818 finishDragAndDrop(entry.displayId, x, y);
2819 return;
2820 }
2821
2822 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2823 // until we have an explicit reason to support it.
2824 constexpr bool isStylus = false;
2825
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002826 sp<WindowInfoHandle> hoverWindowHandle =
2827 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2828 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002829 // enqueue drag exit if needed.
2830 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2831 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2832 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002833 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002834 y);
2835 }
2836 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2837 }
2838 // enqueue drag location if needed.
2839 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002840 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002841 }
2842 break;
2843 }
2844
2845 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002846 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002847 break;
2848 }
2849 // The drag pointer is up.
2850 [[fallthrough]];
2851 case AMOTION_EVENT_ACTION_UP:
2852 finishDragAndDrop(entry.displayId, x, y);
2853 break;
2854 case AMOTION_EVENT_ACTION_CANCEL: {
2855 ALOGD("Receiving cancel when drag and drop.");
2856 sendDropWindowCommandLocked(nullptr, 0, 0);
2857 mDragState.reset();
2858 break;
2859 }
arthurhungb89ccb02020-12-30 16:19:01 +08002860 }
2861}
2862
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002863std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2864 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002865 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002866 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002867 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2868 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002869 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2870 return {};
2871 }
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002872 InputTarget inputTarget{connection};
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002873 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002874 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002875 inputTarget.flags = targetFlags;
2876 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2877 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2878 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2879 if (displayInfoIt != mDisplayInfos.end()) {
2880 inputTarget.displayTransform = displayInfoIt->second.transform;
2881 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002882 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002883 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2884 }
2885 return inputTarget;
2886}
2887
chaviw98318de2021-05-19 16:45:23 -05002888void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002889 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002890 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002891 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002892 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002893 std::vector<InputTarget>::iterator it =
2894 std::find_if(inputTargets.begin(), inputTargets.end(),
2895 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002896 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002897 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002898
chaviw98318de2021-05-19 16:45:23 -05002899 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002900
2901 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002902 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002903 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2904 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002905 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002906 return;
2907 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002908 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002909 it = inputTargets.end() - 1;
2910 }
2911
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002912 if (it->flags != targetFlags) {
2913 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2914 }
2915 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2916 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2917 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2918 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002919}
2920
2921void InputDispatcher::addPointerWindowTargetLocked(
2922 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002923 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2924 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2925 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002926 if (pointerIds.none()) {
2927 for (const auto& target : inputTargets) {
2928 LOG(INFO) << "Target: " << target;
2929 }
2930 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2931 return;
2932 }
2933 std::vector<InputTarget>::iterator it =
2934 std::find_if(inputTargets.begin(), inputTargets.end(),
2935 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002936 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002937 });
2938
2939 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2940 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2941 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2942 // input targets for hovering pointers and for touching pointers.
2943 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2944 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002945 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002946 // Force the code below to create a new input target
2947 it = inputTargets.end();
2948 }
2949
2950 const WindowInfo* windowInfo = windowHandle->getInfo();
2951
2952 if (it == inputTargets.end()) {
2953 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002954 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2955 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002956 if (!target) {
2957 return;
2958 }
2959 inputTargets.push_back(*target);
2960 it = inputTargets.end() - 1;
2961 }
2962
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002963 if (it->dispatchMode != dispatchMode) {
2964 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2965 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2966 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002967 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002968 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2969 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002970 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002971 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002972 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002973 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2974 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002975
chaviw1ff3d1e2020-07-01 15:53:47 -07002976 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977}
2978
Michael Wright3dd60e22019-03-27 22:06:44 +00002979void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002980 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002981 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2982 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002983
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002984 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00002985 InputTarget target{monitor.connection};
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002986 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2987 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002988 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2989 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002990 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002991 target.setDefaultPointerTransform(target.displayTransform);
2992 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994}
2995
Robert Carrc9bf1d32020-04-13 17:21:08 -07002996/**
2997 * Indicate whether one window handle should be considered as obscuring
2998 * another window handle. We only check a few preconditions. Actually
2999 * checking the bounds is left to the caller.
3000 */
chaviw98318de2021-05-19 16:45:23 -05003001static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3002 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003003 // Compare by token so cloned layers aren't counted
3004 if (haveSameToken(windowHandle, otherHandle)) {
3005 return false;
3006 }
3007 auto info = windowHandle->getInfo();
3008 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003009 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003010 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003011 } else if (otherInfo->alpha == 0 &&
3012 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003013 // Those act as if they were invisible, so we don't need to flag them.
3014 // We do want to potentially flag touchable windows even if they have 0
3015 // opacity, since they can consume touches and alter the effects of the
3016 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003017 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003018 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3019 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003020 } else if (info->ownerUid == otherInfo->ownerUid) {
3021 // If ownerUid is the same we don't generate occlusion events as there
3022 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003023 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003024 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003025 return false;
3026 } else if (otherInfo->displayId != info->displayId) {
3027 return false;
3028 }
3029 return true;
3030}
3031
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003032/**
3033 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3034 * untrusted, one should check:
3035 *
3036 * 1. If result.hasBlockingOcclusion is true.
3037 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3038 * BLOCK_UNTRUSTED.
3039 *
3040 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3041 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3042 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3043 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3044 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3045 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3046 *
3047 * If neither of those is true, then it means the touch can be allowed.
3048 */
3049InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003050 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3051 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003052 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003053 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003054 TouchOcclusionInfo info;
3055 info.hasBlockingOcclusion = false;
3056 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003057 info.obscuringUid = gui::Uid::INVALID;
3058 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003059 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003060 if (windowHandle == otherHandle) {
3061 break; // All future windows are below us. Exit early.
3062 }
chaviw98318de2021-05-19 16:45:23 -05003063 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003064 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3065 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003066 if (DEBUG_TOUCH_OCCLUSION) {
3067 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003068 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003069 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003070 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3071 // we perform the checks below to see if the touch can be propagated or not based on the
3072 // window's touch occlusion mode
3073 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3074 info.hasBlockingOcclusion = true;
3075 info.obscuringUid = otherInfo->ownerUid;
3076 info.obscuringPackage = otherInfo->packageName;
3077 break;
3078 }
3079 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003080 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003081 float opacity =
3082 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3083 // Given windows A and B:
3084 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3085 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3086 opacityByUid[uid] = opacity;
3087 if (opacity > info.obscuringOpacity) {
3088 info.obscuringOpacity = opacity;
3089 info.obscuringUid = uid;
3090 info.obscuringPackage = otherInfo->packageName;
3091 }
3092 }
3093 }
3094 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003095 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003096 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003097 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003098 return info;
3099}
3100
chaviw98318de2021-05-19 16:45:23 -05003101std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003102 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003103 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003104 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3105 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3106 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003107 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003108 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003109 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3110 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003111 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3112 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3113 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003114 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003115}
3116
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003117bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3118 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003119 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3120 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003121 return false;
3122 }
3123 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003124 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003125 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003126 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003127 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3128 return false;
3129 }
3130 return true;
3131}
3132
chaviw98318de2021-05-19 16:45:23 -05003133bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003136 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3137 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003138 if (windowHandle == otherHandle) {
3139 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
chaviw98318de2021-05-19 16:45:23 -05003141 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003142 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003143 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 return true;
3145 }
3146 }
3147 return false;
3148}
3149
chaviw98318de2021-05-19 16:45:23 -05003150bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003151 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003152 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3153 const WindowInfo* windowInfo = windowHandle->getInfo();
3154 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003155 if (windowHandle == otherHandle) {
3156 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003157 }
chaviw98318de2021-05-19 16:45:23 -05003158 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003159 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003160 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003161 return true;
3162 }
3163 }
3164 return false;
3165}
3166
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003167std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003168 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003169 if (applicationHandle != nullptr) {
3170 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003171 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 } else {
3173 return applicationHandle->getName();
3174 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003175 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003176 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003178 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
3180}
3181
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003183 if (!isUserActivityEvent(eventEntry)) {
3184 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003185 return;
3186 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003187
3188 const int32_t eventType = getUserActivityEventType(eventEntry);
3189 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3190 // Note that we're directly getting the time diff between the current event and the previous
3191 // event. This is assuming that the first user event always happens at a timestamp that is
3192 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3193 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3194 // value than the potential first user activity event time, so this is ok.
3195 std::chrono::nanoseconds timeSinceLastEvent =
3196 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3197 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3198 return;
3199 }
3200 }
3201
Tiger Huang721e26f2018-07-24 22:26:19 +08003202 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003203 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003204 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003205 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003206 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003207 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003208 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 }
3210 }
3211
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003212 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003213 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3215 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 return;
3217 }
Josep del Riob3981622023-04-18 15:49:45 +00003218 if (windowDisablingUserActivityInfo != nullptr) {
3219 if (DEBUG_DISPATCH_CYCLE) {
3220 ALOGD("Not poking user activity: disabled by window '%s'.",
3221 windowDisablingUserActivityInfo->name.c_str());
3222 }
3223 return;
3224 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003227 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003228 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3229 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230 return;
3231 }
Josep del Riob3981622023-04-18 15:49:45 +00003232 // If the key code is unknown, we don't consider it user activity
3233 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3234 return;
3235 }
3236 // Don't inhibit events that were intercepted or are not passed to
3237 // the apps, like system shortcuts
3238 if (windowDisablingUserActivityInfo != nullptr &&
3239 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3240 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3241 if (DEBUG_DISPATCH_CYCLE) {
3242 ALOGD("Not poking user activity: disabled by window '%s'.",
3243 windowDisablingUserActivityInfo->name.c_str());
3244 }
3245 return;
3246 }
3247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003250 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003251 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003252 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003253 break;
3254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
3256
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003257 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003258 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3259 REQUIRES(mLock) {
3260 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003261 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003262 };
3263 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264}
3265
3266void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003267 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003268 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003269 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003270 ATRACE_NAME_IF(ATRACE_ENABLED(),
3271 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3272 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003273 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003275 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003277 inputTarget.globalScaleFactor, bitsetToString(inputTarget.getPointerIds()).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003278 inputTarget.getPointerInfoString().c_str());
3279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280
3281 // Skip this event if the connection status is not normal.
3282 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003283 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003284 if (DEBUG_DISPATCH_CYCLE) {
3285 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003286 connection->getInputChannelName().c_str(),
3287 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 return;
3290 }
3291
3292 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003293 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003294 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003296 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003298 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003299 if (inputTarget.getPointerIds().count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003300 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3301 logDispatchStateLocked();
3302 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3303 "target on connection "
3304 << connection->getInputChannelName() << " for "
3305 << originalMotionEntry.getDescription();
3306 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhanc32a4112024-01-23 23:20:37 +00003308 splitMotionEvent(originalMotionEntry, inputTarget.getPointerIds(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003309 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 if (!splitMotionEntry) {
3311 return; // split event was dropped
3312 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003313 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3314 std::string reason = std::string("reason=pointer cancel on split window");
3315 android_log_event_list(LOGTAG_INPUT_CANCEL)
3316 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3317 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003318 if (DEBUG_FOCUS) {
3319 ALOGD("channel '%s' ~ Split motion event.",
3320 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003321 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003322 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003323 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3324 std::move(splitMotionEntry),
3325 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 return;
3327 }
3328 }
3329
3330 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003331 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3332 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333}
3334
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003335void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3336 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3337 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003338 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3340 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003341 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003342
hongzuo liu95785e22022-09-06 02:51:35 +00003343 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003345 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
3347 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003348 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 startDispatchCycleLocked(currentTime, connection);
3350 }
3351}
3352
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003353void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003354 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003355 const InputTarget& inputTarget) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00003356 const bool isKeyOrMotion = eventEntry->type == EventEntry::Type::KEY ||
3357 eventEntry->type == EventEntry::Type::MOTION;
3358 if (isKeyOrMotion && !inputTarget.windowHandle && !connection->monitor) {
3359 LOG(FATAL) << "All InputTargets for non-monitors must be associated with a window; target: "
3360 << inputTarget << " connection: " << connection->getInputChannelName()
3361 << " entry: " << eventEntry->getDescription();
3362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 // This is a new event.
3364 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003365 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003366 createDispatchEntry(mIdGenerator, inputTarget, eventEntry, inputTarget.flags,
3367 mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003369 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3370 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003371 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003373 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003374 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003375 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3376 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003377 LOG(WARNING) << "channel " << connection->getInputChannelName()
3378 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 return; // skip the inconsistent event
3380 }
3381 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003384 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003385 std::shared_ptr<const MotionEntry> resolvedMotion =
3386 std::static_pointer_cast<const MotionEntry>(eventEntry);
3387 {
3388 // Determine the resolved motion entry.
3389 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3390 int32_t resolvedAction = motionEntry.action;
3391 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003393 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003394 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003395 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003396 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003397 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003398 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003399 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003400 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003401 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003402 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3403 }
3404 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3405 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3406 motionEntry.displayId)) {
3407 if (DEBUG_DISPATCH_CYCLE) {
3408 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3409 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3410 "enter event";
3411 }
3412 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3413 }
3414
3415 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3416 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3417 }
3418 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3419 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3420 }
3421 if (dispatchEntry->targetFlags.test(
3422 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3423 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3424 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003425 if (dispatchEntry->targetFlags.test(InputTarget::Flags::NO_FOCUS_CHANGE)) {
3426 resolvedFlags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
3427 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003428
3429 dispatchEntry->resolvedFlags = resolvedFlags;
3430 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003431 std::optional<std::vector<PointerProperties>> usingProperties;
3432 std::optional<std::vector<PointerCoords>> usingCoords;
3433 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3434 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3435 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3436 // the dispatcher, and therefore the coordinates of this event are currently
3437 // incorrect. These events should use the coordinates of the last dispatched
3438 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3439 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3440 std::optional<std::pair<std::vector<PointerProperties>,
3441 std::vector<PointerCoords>>>
3442 pointerInfo =
3443 connection->inputState.getPointersOfLastEvent(motionEntry,
3444 hovering);
3445 if (pointerInfo) {
3446 usingProperties = pointerInfo->first;
3447 usingCoords = pointerInfo->second;
3448 }
3449 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003450 // Generate a new MotionEntry with a new eventId using the resolved action and
3451 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003452 resolvedMotion = std::make_shared<
3453 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3454 motionEntry.eventTime, motionEntry.deviceId,
3455 motionEntry.source, motionEntry.displayId,
3456 motionEntry.policyFlags, resolvedAction,
3457 motionEntry.actionButton, resolvedFlags,
3458 motionEntry.metaState, motionEntry.buttonState,
3459 motionEntry.classification, motionEntry.edgeFlags,
3460 motionEntry.xPrecision, motionEntry.yPrecision,
3461 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3462 motionEntry.downTime,
3463 usingProperties.value_or(motionEntry.pointerProperties),
3464 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003465 if (ATRACE_ENABLED()) {
3466 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3467 ") to MotionEvent(id=0x%" PRIx32 ").",
3468 motionEntry.id, resolvedMotion->id);
3469 ATRACE_NAME(message.c_str());
3470 }
3471
3472 // Set the resolved motion entry in the DispatchEntry.
3473 dispatchEntry->eventEntry = resolvedMotion;
3474 eventEntry = resolvedMotion;
3475 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003478 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3479 // devices being active at the same time in the same window, so if a new device is
3480 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003481 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003482 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003483 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003484 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003485 << connection->getInputChannelName() << " with event "
3486 << cancelEvent->getDescription();
3487 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003488 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003489 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003490
3491 // Send these cancel events to the queue before sending the event from the new
3492 // device.
3493 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3494 }
3495
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003496 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003497 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003498 LOG(WARNING) << "channel " << connection->getInputChannelName()
3499 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 return; // skip the inconsistent event
3501 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00003502 if ((dispatchEntry->resolvedFlags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003503 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003504 // Skip reporting pointer down outside focus to the policy.
3505 break;
3506 }
3507
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003508 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003509 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510
3511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003513 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003514 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003515 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3516 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003517 break;
3518 }
Chris Yef59a2f42020-10-16 12:55:26 -07003519 case EventEntry::Type::SENSOR: {
3520 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3521 break;
3522 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003523 case EventEntry::Type::CONFIGURATION_CHANGED:
3524 case EventEntry::Type::DEVICE_RESET: {
3525 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003526 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003527 break;
3528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530
3531 // Remember that we are waiting for this dispatch to complete.
3532 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003533 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535
3536 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003537 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003538 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003539}
3540
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003541/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003542 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003543 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003544 * The first role is to log input interaction with windows, which helps determine what the user was
3545 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3546 * that user started interacting with launcher window, as well as any other window that received
3547 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3548 * when the set of tokens that received the event changes. It is not logged again as long as the
3549 * user is interacting with the same windows.
3550 *
3551 * The second role is to track input device activity for metrics collection. For each input event,
3552 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3553 * input_interaction logs, the device interaction is reported even when the set of interaction
3554 * tokens do not change.
3555 *
3556 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3557 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003558 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003559void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3560 const std::vector<InputTarget>& targets) {
3561 int32_t deviceId;
3562 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003563 // Skip ACTION_UP events, and all events other than keys and motions
3564 if (entry.type == EventEntry::Type::KEY) {
3565 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3566 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3567 return;
3568 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003569 deviceId = keyEntry.deviceId;
3570 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003571 } else if (entry.type == EventEntry::Type::MOTION) {
3572 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3573 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003574 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3575 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003576 return;
3577 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003578 deviceId = motionEntry.deviceId;
3579 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 } else {
3581 return; // Not a key or a motion
3582 }
3583
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003584 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003585 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003586 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003587 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003588 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003589 continue; // Skip windows that receive ACTION_OUTSIDE
3590 }
3591
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003592 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003594 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003595 if (target.windowHandle) {
3596 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3597 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003598 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003599
3600 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3601 REQUIRES(mLock) {
3602 scoped_unlock unlock(mLock);
3603 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3604 };
3605 postCommandLocked(std::move(command));
3606
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003607 if (newConnectionTokens == mInteractionConnectionTokens) {
3608 return; // no change
3609 }
3610 mInteractionConnectionTokens = newConnectionTokens;
3611
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003612 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003613 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003614 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003615 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003616 std::string message = "Interaction with: " + targetList;
3617 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003618 message += "<none>";
3619 }
3620 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3621}
3622
chaviwfd6d3512019-03-25 13:23:49 -07003623void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003624 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003625 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003626 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3627 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003628 return;
3629 }
3630
Vishnu Nairc519ff72021-01-21 08:23:08 -08003631 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003632 if (focusedToken == token) {
3633 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003634 return;
3635 }
3636
Prabir Pradhancef936d2021-07-21 16:17:52 +00003637 auto command = [this, token]() REQUIRES(mLock) {
3638 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003639 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003640 };
3641 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642}
3643
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003644status_t InputDispatcher::publishMotionEvent(Connection& connection,
3645 DispatchEntry& dispatchEntry) const {
3646 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3647 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3648
3649 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003650 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003651
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003652 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003653 // Set the X and Y offset and X and Y scale depending on the input source.
3654 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003655 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003656 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3657 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003658 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003659 scaledCoords[i] = motionEntry.pointerCoords[i];
3660 // Don't apply window scale here since we don't want scale to affect raw
3661 // coordinates. The scale will be sent back to the client and applied
3662 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003663 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003664 }
3665 usingCoords = scaledCoords;
3666 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003667 }
3668
3669 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3670
3671 // Publish the motion event.
3672 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003673 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3674 motionEntry.source, motionEntry.displayId, std::move(hmac),
3675 motionEntry.action, motionEntry.actionButton,
3676 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3677 motionEntry.metaState, motionEntry.buttonState,
3678 motionEntry.classification, dispatchEntry.transform,
3679 motionEntry.xPrecision, motionEntry.yPrecision,
3680 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3681 dispatchEntry.rawTransform, motionEntry.downTime,
3682 motionEntry.eventTime, motionEntry.getPointerCount(),
3683 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003684}
3685
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003687 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003688 ATRACE_NAME_IF(ATRACE_ENABLED(),
3689 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3690 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003691 if (DEBUG_DISPATCH_CYCLE) {
3692 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003695 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003696 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003698 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003699 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700
3701 // Publish the event.
3702 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003703 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3704 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003705 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003706 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3707 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003708 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003709 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3710 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003713 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003714 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003715 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3716 keyEntry.deviceId, keyEntry.source,
3717 keyEntry.displayId, std::move(hmac),
3718 keyEntry.action, dispatchEntry->resolvedFlags,
3719 keyEntry.keyCode, keyEntry.scanCode,
3720 keyEntry.metaState, keyEntry.repeatCount,
3721 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003722 if (mTracer) {
3723 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3724 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
3727
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003728 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003730 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3731 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003732 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003733 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003734 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003735 if (mTracer) {
3736 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3737 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003738 break;
3739 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003740
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003741 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003742 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003743 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003745 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003746 break;
3747 }
3748
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003749 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3750 const TouchModeEntry& touchModeEntry =
3751 static_cast<const TouchModeEntry&>(eventEntry);
3752 status = connection->inputPublisher
3753 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3754 touchModeEntry.inTouchMode);
3755
3756 break;
3757 }
3758
Prabir Pradhan99987712020-11-10 18:43:05 -08003759 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3760 const auto& captureEntry =
3761 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3762 status = connection->inputPublisher
3763 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003764 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003765 break;
3766 }
3767
arthurhungb89ccb02020-12-30 16:19:01 +08003768 case EventEntry::Type::DRAG: {
3769 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3770 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3771 dragEntry.id, dragEntry.x,
3772 dragEntry.y,
3773 dragEntry.isExiting);
3774 break;
3775 }
3776
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003777 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003778 case EventEntry::Type::DEVICE_RESET:
3779 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003780 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003781 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785
3786 // Check the result.
3787 if (status) {
3788 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003789 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 "This is unexpected because the wait queue is empty, so the pipe "
3792 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003793 "event to it, status=%s(%d)",
3794 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3795 status);
Harry Cutts33476232023-01-30 19:57:29 +00003796 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 } else {
3798 // Pipe is full and we are waiting for the app to finish process some events
3799 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003800 if (DEBUG_DISPATCH_CYCLE) {
3801 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3802 "waiting for the application to catch up",
3803 connection->getInputChannelName().c_str());
3804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806 } else {
3807 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003808 "status=%s(%d)",
3809 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3810 status);
Harry Cutts33476232023-01-30 19:57:29 +00003811 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813 return;
3814 }
3815
3816 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003817 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3818 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3819 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003820 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003821 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003822 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003823 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003824 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 }
3826}
3827
chaviw09c8d2d2020-08-24 15:48:26 -07003828std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3829 size_t size;
3830 switch (event.type) {
3831 case VerifiedInputEvent::Type::KEY: {
3832 size = sizeof(VerifiedKeyEvent);
3833 break;
3834 }
3835 case VerifiedInputEvent::Type::MOTION: {
3836 size = sizeof(VerifiedMotionEvent);
3837 break;
3838 }
3839 }
3840 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3841 return mHmacKeyManager.sign(start, size);
3842}
3843
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003844const std::array<uint8_t, 32> InputDispatcher::getSignature(
3845 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003846 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003847 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003848 // Only sign events up and down events as the purely move events
3849 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003850 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003851 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003852
3853 VerifiedMotionEvent verifiedEvent =
3854 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3855 verifiedEvent.actionMasked = actionMasked;
3856 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3857 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003858}
3859
3860const std::array<uint8_t, 32> InputDispatcher::getSignature(
3861 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3862 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3863 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003864 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003865}
3866
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003868 const std::shared_ptr<Connection>& connection,
3869 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003870 if (DEBUG_DISPATCH_CYCLE) {
3871 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3872 connection->getInputChannelName().c_str(), seq, toString(handled));
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003875 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 return;
3877 }
3878
3879 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003880 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3881 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3882 };
3883 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884}
3885
3886void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003887 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003888 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003889 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003890 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3891 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893
3894 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003895 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003896 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003897 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003898 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899
3900 // The connection appears to be unrecoverably broken.
3901 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003902 if (connection->status == Connection::Status::NORMAL) {
3903 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
3905 if (notify) {
3906 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003907 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3908 connection->getInputChannelName().c_str());
3909
3910 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003911 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003912 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003913 };
3914 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916 }
3917}
3918
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003919void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003920 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003921 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003922 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
3924}
3925
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003926void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003928 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930}
3931
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003932int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3933 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003934 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003935 if (connection == nullptr) {
3936 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3937 connectionToken.get(), events);
3938 return 0; // remove the callback
3939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003941 bool notify;
3942 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3943 if (!(events & ALOOPER_EVENT_INPUT)) {
3944 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3945 "events=0x%x",
3946 connection->getInputChannelName().c_str(), events);
3947 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 }
3949
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003950 nsecs_t currentTime = now();
3951 bool gotOne = false;
3952 status_t status = OK;
3953 for (;;) {
3954 Result<InputPublisher::ConsumerResponse> result =
3955 connection->inputPublisher.receiveConsumerResponse();
3956 if (!result.ok()) {
3957 status = result.error().code();
3958 break;
3959 }
3960
3961 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3962 const InputPublisher::Finished& finish =
3963 std::get<InputPublisher::Finished>(*result);
3964 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3965 finish.consumeTime);
3966 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003967 if (shouldReportMetricsForConnection(*connection)) {
3968 const InputPublisher::Timeline& timeline =
3969 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003970 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3971 connection->getToken(),
3972 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003973 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003974 }
3975 gotOne = true;
3976 }
3977 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003978 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003979 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 return 1;
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003984 notify = status != DEAD_OBJECT || !connection->monitor;
3985 if (notify) {
3986 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3987 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3988 status);
3989 }
3990 } else {
3991 // Monitor channels are never explicitly unregistered.
3992 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003993 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003994 notify = !connection->monitor && stillHaveWindowHandle;
3995 if (notify) {
3996 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3997 connection->getInputChannelName().c_str(), events);
3998 }
3999 }
4000
4001 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004002 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004003 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004}
4005
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004008 // Cancel windows (i.e. non-monitors).
4009 // A channel must have at least one window to receive any input. If a window was removed, the
4010 // event streams directed to the window will already have been canceled during window removal.
4011 // So there is no need to generate cancellations for connections without any windows.
4012 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4013 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4014 // through a non-touched window if there are more than one window for an input channel.
4015 if (cancelPointers) {
4016 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4017 if (options.displayId.has_value() && options.displayId != displayId) {
4018 continue;
4019 }
4020 for (const auto& touchedWindow : touchState.windows) {
4021 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4022 }
4023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004025 // Follow up by generating cancellations for all windows, because we don't explicitly track
4026 // the windows that have an ongoing focus event stream.
4027 if (cancelNonPointers) {
4028 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4029 for (const auto& windowHandle : handles) {
4030 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4031 }
4032 }
4033 }
4034
4035 // Cancel monitors.
4036 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004040 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004041 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004042 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004043 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4044 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004045 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004046 }
4047}
4048
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004049void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4050 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4051 const std::shared_ptr<Connection>& connection) {
4052 if (windowHandle == nullptr) {
4053 LOG(FATAL) << __func__ << ": Window handle must not be null";
4054 }
4055 if (connection) {
4056 // The connection can be optionally provided to avoid multiple lookups.
4057 if (windowHandle->getToken() != connection->getToken()) {
4058 LOG(FATAL) << __func__
4059 << ": Wrong connection provided for window: " << windowHandle->getName();
4060 }
4061 }
4062
4063 std::shared_ptr<Connection> resolvedConnection =
4064 connection ? connection : getConnectionLocked(windowHandle->getToken());
4065 if (!resolvedConnection) {
4066 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4067 return;
4068 }
4069 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4070}
4071
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004073 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4074 const sp<WindowInfoHandle>& window) {
4075 if (!connection->monitor && window == nullptr) {
4076 LOG(FATAL) << __func__
4077 << ": Cannot send event to non-monitor channel without a window - channel: "
4078 << connection->getInputChannelName();
4079 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004080 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 return;
4082 }
4083
4084 nsecs_t currentTime = now();
4085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004087 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004089 if (cancelationEvents.empty()) {
4090 return;
4091 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004092
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4094 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004095 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004097 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004098 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004099
Arthur Hungb3307ee2021-10-14 10:57:37 +00004100 std::string reason = std::string("reason=").append(options.reason);
4101 android_log_event_list(LOGTAG_INPUT_CANCEL)
4102 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4103
hongzuo liu95785e22022-09-06 02:51:35 +00004104 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004105 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004106 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004107 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004108
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004109 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004111 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004112
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004113 switch (cancelationEventEntry->type) {
4114 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004115 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004116 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004117 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4118 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004119 } else {
4120 targets.emplace_back(fallbackTarget);
4121 }
4122 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004123 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004125 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004126 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004127 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004128 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004129 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004130 pointerIndex++) {
4131 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4132 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004133 if (mDragState && mDragState->dragWindow->getToken() == token &&
4134 pointerIds.test(mDragState->pointerId)) {
4135 LOG(INFO) << __func__
4136 << ": Canceling drag and drop because the pointers for the drag "
4137 "window are being canceled.";
4138 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4139 mDragState.reset();
4140 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004141 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4142 ftl::Flags<InputTarget::Flags>(), pointerIds,
4143 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004144 } else {
4145 targets.emplace_back(fallbackTarget);
4146 const auto it = mDisplayInfos.find(motionEntry.displayId);
4147 if (it != mDisplayInfos.end()) {
4148 targets.back().displayTransform = it->second.transform;
4149 targets.back().setDefaultPointerTransform(it->second.transform);
4150 }
4151 }
4152 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004155 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004156 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004157 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4158 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004159 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004160 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004161 break;
4162 }
4163 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004164 case EventEntry::Type::DEVICE_RESET:
4165 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004166 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004167 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004168 break;
4169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004172 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004173 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004175
hongzuo liu95785e22022-09-06 02:51:35 +00004176 // If the outbound queue was previously empty, start the dispatch cycle going.
4177 if (wasEmpty && !connection->outboundQueue.empty()) {
4178 startDispatchCycleLocked(currentTime, connection);
4179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180}
4181
Svet Ganov5d3bc372020-01-26 23:11:07 -08004182void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004183 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004184 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004185 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004186 return;
4187 }
4188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004189 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004190 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004191
4192 if (downEvents.empty()) {
4193 return;
4194 }
4195
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004196 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4198 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004199 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004200
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004201 const auto [_, touchedWindowState, displayId] =
4202 findTouchStateWindowAndDisplayLocked(connection->getToken());
4203 if (touchedWindowState == nullptr) {
4204 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4205 }
4206 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004207
hongzuo liu95785e22022-09-06 02:51:35 +00004208 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004209 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004210 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004211 switch (downEventEntry->type) {
4212 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004213 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4214 if (windowHandle != nullptr) {
4215 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004216 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004217 pointerIndex++) {
4218 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4219 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004220 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4221 targetFlags, pointerIds, motionEntry.downTime,
4222 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004223 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004224 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004225 const auto it = mDisplayInfos.find(motionEntry.displayId);
4226 if (it != mDisplayInfos.end()) {
4227 targets.back().displayTransform = it->second.transform;
4228 targets.back().setDefaultPointerTransform(it->second.transform);
4229 }
4230 }
4231 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004232 break;
4233 }
4234
4235 case EventEntry::Type::KEY:
4236 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004237 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004238 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004239 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004240 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004241 case EventEntry::Type::SENSOR:
4242 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004243 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004244 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004245 break;
4246 }
4247 }
4248
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004249 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004250 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004251 }
4252
hongzuo liu95785e22022-09-06 02:51:35 +00004253 // If the outbound queue was previously empty, start the dispatch cycle going.
4254 if (wasEmpty && !connection->outboundQueue.empty()) {
4255 startDispatchCycleLocked(downTime, connection);
4256 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004257}
4258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004259std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004260 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4261 nsecs_t splitDownTime) {
4262 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263
4264 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004265 std::vector<PointerProperties> splitPointerProperties;
4266 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004268 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 uint32_t splitPointerCount = 0;
4270
4271 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004274 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004276 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004278 splitPointerProperties.push_back(pointerProperties);
4279 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 splitPointerCount += 1;
4281 }
4282 }
4283
4284 if (splitPointerCount != pointerIds.count()) {
4285 // This is bad. We are missing some of the pointers that we expected to deliver.
4286 // Most likely this indicates that we received an ACTION_MOVE events that has
4287 // different pointer ids than we expected based on the previous ACTION_DOWN
4288 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4289 // in this way.
4290 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004291 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004292 "a broken sequence of pointer ids from the input device: %s",
4293 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004294 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
4296
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004297 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4300 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004301 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004303 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004305 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 if (pointerIds.count() == 1) {
4307 // The first/last pointer went down/up.
4308 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004310 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4311 ? AMOTION_EVENT_ACTION_CANCEL
4312 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 } else {
4314 // A secondary pointer went down/up.
4315 uint32_t splitPointerIndex = 0;
4316 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4317 splitPointerIndex += 1;
4318 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004319 action = maskedAction |
4320 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322 } else {
4323 // An unrelated pointer changed.
4324 action = AMOTION_EVENT_ACTION_MOVE;
4325 }
4326 }
4327
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004328 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4329 logDispatchStateLocked();
4330 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4331 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4332 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004333 }
4334
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004335 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004336 ATRACE_NAME_IF(ATRACE_ENABLED(),
4337 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4338 ").",
4339 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004341 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4342 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004343 originalMotionEntry.deviceId, originalMotionEntry.source,
4344 originalMotionEntry.displayId,
4345 originalMotionEntry.policyFlags, action,
4346 originalMotionEntry.actionButton,
4347 originalMotionEntry.flags, originalMotionEntry.metaState,
4348 originalMotionEntry.buttonState,
4349 originalMotionEntry.classification,
4350 originalMotionEntry.edgeFlags,
4351 originalMotionEntry.xPrecision,
4352 originalMotionEntry.yPrecision,
4353 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004354 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004355 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 return splitMotionEntry;
4358}
4359
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004360void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4361 std::scoped_lock _l(mLock);
4362 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4363}
4364
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004365void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004366 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004367 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
Antonio Kantekf16f2832021-09-28 04:39:20 +00004370 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004372 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004374 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004375 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004376 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 } // release lock
4378
4379 if (needWake) {
4380 mLooper->wake();
4381 }
4382}
4383
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004384void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004385 ALOGD_IF(debugInboundEventDetails(),
4386 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4387 ", deviceId=%d, source=%s, displayId=%" PRId32
4388 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4389 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004390 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4391 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4392 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004393 Result<void> keyCheck = validateKeyEvent(args.action);
4394 if (!keyCheck.ok()) {
4395 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 return;
4397 }
4398
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004399 uint32_t policyFlags = args.policyFlags;
4400 int32_t flags = args.flags;
4401 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004402 // InputDispatcher tracks and generates key repeats on behalf of
4403 // whatever notifies it, so repeatCount should always be set to 0
4404 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4406 policyFlags |= POLICY_FLAG_VIRTUAL;
4407 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 if (policyFlags & POLICY_FLAG_FUNCTION) {
4410 metaState |= AMETA_FUNCTION_ON;
4411 }
4412
4413 policyFlags |= POLICY_FLAG_TRUSTED;
4414
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004415 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004417 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4418 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4419 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
Michael Wright2b3c3302018-03-02 17:19:13 +00004421 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004422 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004423 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4424 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004425 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427
Antonio Kantekf16f2832021-09-28 04:39:20 +00004428 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 { // acquire lock
4430 mLock.lock();
4431
4432 if (shouldSendKeyToInputFilterLocked(args)) {
4433 mLock.unlock();
4434
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004435 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004436 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 return; // event was consumed by the filter
4438 }
4439
4440 mLock.lock();
4441 }
4442
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004444 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4445 args.deviceId, args.source, args.displayId, policyFlags,
4446 args.action, flags, keyCode, args.scanCode, metaState,
4447 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004448 if (mTracer) {
4449 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004452 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 mLock.unlock();
4454 } // release lock
4455
4456 if (needWake) {
4457 mLooper->wake();
4458 }
4459}
4460
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004461bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 return mInputFilterEnabled;
4463}
4464
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004466 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004467 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004469 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004470 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4471 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004472 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4473 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4474 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4475 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4476 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004477 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004478 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4479 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004480 i, args.pointerProperties[i].id,
4481 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4482 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4483 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4484 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4485 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4486 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4487 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4488 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4489 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4490 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004493
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004494 Result<void> motionCheck =
4495 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4496 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004497 if (!motionCheck.ok()) {
4498 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4499 return;
4500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004502 if (DEBUG_VERIFY_EVENTS) {
4503 auto [it, _] =
4504 mVerifiersByDisplay.try_emplace(args.displayId,
4505 StringPrintf("display %" PRId32, args.displayId));
4506 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004507 it->second.processMovement(args.deviceId, args.source, args.action,
4508 args.getPointerCount(), args.pointerProperties.data(),
4509 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004510 if (!result.ok()) {
4511 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4512 }
4513 }
4514
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004515 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004517
4518 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004519 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4520 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004521 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4522 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Antonio Kantekf16f2832021-09-28 04:39:20 +00004526 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 { // acquire lock
4528 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004529 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4530 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4531 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004532 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004533 if (touchStateIt != mTouchStatesByDisplay.end()) {
4534 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004535 if (touchState.hasTouchingPointers(args.deviceId) ||
4536 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004537 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4538 }
4539 }
4540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541
4542 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004543 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004544 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004545 displayTransform = it->second.transform;
4546 }
4547
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 mLock.unlock();
4549
4550 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004551 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4552 args.action, args.actionButton, args.flags, args.edgeFlags,
4553 args.metaState, args.buttonState, args.classification,
4554 displayTransform, args.xPrecision, args.yPrecision,
4555 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004556 args.downTime, args.eventTime, args.getPointerCount(),
4557 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558
4559 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004560 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 return; // event was consumed by the filter
4562 }
4563
4564 mLock.lock();
4565 }
4566
4567 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004568 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004569 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4570 args.deviceId, args.source, args.displayId,
4571 policyFlags, args.action, args.actionButton,
4572 args.flags, args.metaState, args.buttonState,
4573 args.classification, args.edgeFlags, args.xPrecision,
4574 args.yPrecision, args.xCursorPosition,
4575 args.yCursorPosition, args.downTime,
4576 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004577 if (mTracer) {
4578 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004581 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4582 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004583 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004584 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004585 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4586 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4587 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004588 }
4589
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004590 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 mLock.unlock();
4592 } // release lock
4593
4594 if (needWake) {
4595 mLooper->wake();
4596 }
4597}
4598
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004599void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004600 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004601 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4602 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004603 args.id, args.eventTime, args.deviceId, args.source,
4604 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004605 }
Chris Yef59a2f42020-10-16 12:55:26 -07004606
Antonio Kantekf16f2832021-09-28 04:39:20 +00004607 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004608 { // acquire lock
4609 mLock.lock();
4610
4611 // Just enqueue a new sensor event.
4612 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4614 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4615 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004616
4617 needWake = enqueueInboundEventLocked(std::move(newEntry));
4618 mLock.unlock();
4619 } // release lock
4620
4621 if (needWake) {
4622 mLooper->wake();
4623 }
4624}
4625
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004626void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004627 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004628 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4629 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004630 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004631 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004632}
4633
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004634bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004635 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636}
4637
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004638void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004639 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004640 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4641 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004642 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004645 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004647 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648}
4649
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004651 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004652 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4653 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655
Antonio Kantekf16f2832021-09-28 04:39:20 +00004656 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004658 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004660 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004661 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004662 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004663
4664 for (auto& [_, verifier] : mVerifiersByDisplay) {
4665 verifier.resetDevice(args.deviceId);
4666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 } // release lock
4668
4669 if (needWake) {
4670 mLooper->wake();
4671 }
4672}
4673
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004674void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004675 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004676 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4677 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004678 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004679
Antonio Kantekf16f2832021-09-28 04:39:20 +00004680 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004681 { // acquire lock
4682 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004683 auto entry =
4684 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004685 needWake = enqueueInboundEventLocked(std::move(entry));
4686 } // release lock
4687
4688 if (needWake) {
4689 mLooper->wake();
4690 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004691}
4692
Prabir Pradhan5735a322022-04-11 17:23:34 +00004693InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004694 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004695 InputEventInjectionSync syncMode,
4696 std::chrono::milliseconds timeout,
4697 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004698 Result<void> eventValidation = validateInputEvent(*event);
4699 if (!eventValidation.ok()) {
4700 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4701 return InputEventInjectionResult::FAILED;
4702 }
4703
Prabir Pradhan65613802023-02-22 23:36:58 +00004704 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004705 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4706 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4707 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4708 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004709 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004710 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711
Prabir Pradhan5735a322022-04-11 17:23:34 +00004712 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004714 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004715 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4716 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4717 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4718 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4719 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004720 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004721 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004722 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004723 }
4724
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004725 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4726 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4727
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004728 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004730 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004731 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004732 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004733 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004734 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4735 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4736 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004737 int32_t keyCode = incomingKey.getKeyCode();
4738 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004739 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004740 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004741 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4742 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4743 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4746 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004747 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748
4749 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4750 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004751 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4753 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4754 std::to_string(t.duration().count()).c_str());
4755 }
4756 }
4757
4758 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004759 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004760 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4761 incomingKey.getEventTime(), resolvedDeviceId,
4762 incomingKey.getSource(), incomingKey.getDisplayId(),
4763 policyFlags, action, flags, keyCode,
4764 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004765 incomingKey.getRepeatCount(),
4766 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004767 if (mTracer) {
4768 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004770 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004774 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004775 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004776 const bool isPointerEvent =
4777 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4778 // If a pointer event has no displayId specified, inject it to the default display.
4779 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4780 ? ADISPLAY_ID_DEFAULT
4781 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004782 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004783
4784 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004785 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004787 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4788 motionEvent.getAction(), eventTime,
4789 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004790 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4791 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4792 std::to_string(t.duration().count()).c_str());
4793 }
4794 }
4795
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004796 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4797 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4798 }
4799
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004801 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004802 const size_t pointerCount = motionEvent.getPointerCount();
4803 const std::vector<PointerProperties>
4804 pointerProperties(motionEvent.getPointerProperties(),
4805 motionEvent.getPointerProperties() + pointerCount);
4806
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004807 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004808 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004809 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4810 *sampleEventTimes, resolvedDeviceId,
4811 motionEvent.getSource(), displayId, policyFlags,
4812 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004813 motionEvent.getActionButton(), flags,
4814 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004815 motionEvent.getButtonState(),
4816 motionEvent.getClassification(),
4817 motionEvent.getEdgeFlags(),
4818 motionEvent.getXPrecision(),
4819 motionEvent.getYPrecision(),
4820 motionEvent.getRawXCursorPosition(),
4821 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004822 motionEvent.getDownTime(), pointerProperties,
4823 std::vector<PointerCoords>(samplePointerCoords,
4824 samplePointerCoords +
4825 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004826 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004827 if (mTracer) {
4828 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4829 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004830 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004831 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004833 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004834 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004835 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4836 resolvedDeviceId, motionEvent.getSource(), displayId,
4837 policyFlags, motionEvent.getAction(),
4838 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004839 motionEvent.getMetaState(), motionEvent.getButtonState(),
4840 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4841 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4842 motionEvent.getRawXCursorPosition(),
4843 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4844 pointerProperties,
4845 std::vector<PointerCoords>(samplePointerCoords,
4846 samplePointerCoords +
4847 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004848 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4849 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004850 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004851 }
4852 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004856 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 }
4859
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004861 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004862 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004863 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004865 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004866 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868
4869 mLock.unlock();
4870
4871 if (needWake) {
4872 mLooper->wake();
4873 }
4874
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004877 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004879 if (syncMode == InputEventInjectionSync::NONE) {
4880 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 } else {
4882 for (;;) {
4883 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004884 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 break;
4886 }
4887
4888 nsecs_t remainingTimeout = endTime - now();
4889 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004890 if (DEBUG_INJECTION) {
4891 ALOGD("injectInputEvent - Timed out waiting for injection result "
4892 "to become available.");
4893 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004894 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 break;
4896 }
4897
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004898 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 }
4900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4902 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004904 if (DEBUG_INJECTION) {
4905 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4906 injectionState->pendingForegroundDispatches);
4907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 nsecs_t remainingTimeout = endTime - now();
4909 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004910 if (DEBUG_INJECTION) {
4911 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4912 "dispatches to finish.");
4913 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004914 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 break;
4916 }
4917
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004918 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 }
4920 }
4921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 } // release lock
4923
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004924 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004925 LOG(INFO) << "injectInputEvent - Finished with result "
4926 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928
4929 return injectionResult;
4930}
4931
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004932std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004933 std::array<uint8_t, 32> calculatedHmac;
4934 std::unique_ptr<VerifiedInputEvent> result;
4935 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004936 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004937 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4938 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4939 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004940 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004941 break;
4942 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004943 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004944 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4945 VerifiedMotionEvent verifiedMotionEvent =
4946 verifiedMotionEventFromMotionEvent(motionEvent);
4947 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004948 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004949 break;
4950 }
4951 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004952 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004953 return nullptr;
4954 }
4955 }
4956 if (calculatedHmac == INVALID_HMAC) {
4957 return nullptr;
4958 }
tyiu1573a672023-02-21 22:38:32 +00004959 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004960 return nullptr;
4961 }
4962 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004963}
4964
Prabir Pradhan24047542023-11-02 17:14:59 +00004965void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004966 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004967 if (!entry.injectionState) {
4968 // Not an injected event.
4969 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004971
4972 InjectionState& injectionState = *entry.injectionState;
4973 if (DEBUG_INJECTION) {
4974 LOG(INFO) << "Setting input event injection result to "
4975 << ftl::enum_string(injectionResult);
4976 }
4977
4978 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4979 // Log the outcome since the injector did not wait for the injection result.
4980 switch (injectionResult) {
4981 case InputEventInjectionResult::SUCCEEDED:
4982 ALOGV("Asynchronous input event injection succeeded.");
4983 break;
4984 case InputEventInjectionResult::TARGET_MISMATCH:
4985 ALOGV("Asynchronous input event injection target mismatch.");
4986 break;
4987 case InputEventInjectionResult::FAILED:
4988 ALOGW("Asynchronous input event injection failed.");
4989 break;
4990 case InputEventInjectionResult::TIMED_OUT:
4991 ALOGW("Asynchronous input event injection timed out.");
4992 break;
4993 case InputEventInjectionResult::PENDING:
4994 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4995 break;
4996 }
4997 }
4998
4999 injectionState.injectionResult = injectionResult;
5000 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001}
5002
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005003void InputDispatcher::transformMotionEntryForInjectionLocked(
5004 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005005 // Input injection works in the logical display coordinate space, but the input pipeline works
5006 // display space, so we need to transform the injected events accordingly.
5007 const auto it = mDisplayInfos.find(entry.displayId);
5008 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005009 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005010
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005011 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5012 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5013 const vec2 cursor =
5014 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5015 {entry.xCursorPosition, entry.yCursorPosition});
5016 entry.xCursorPosition = cursor.x;
5017 entry.yCursorPosition = cursor.y;
5018 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005019 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005020 entry.pointerCoords[i] =
5021 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5022 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005023 }
5024}
5025
Prabir Pradhan24047542023-11-02 17:14:59 +00005026void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005027 if (entry.injectionState) {
5028 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 }
5030}
5031
Prabir Pradhan24047542023-11-02 17:14:59 +00005032void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005033 if (entry.injectionState) {
5034 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005036 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005037 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039 }
5040}
5041
chaviw98318de2021-05-19 16:45:23 -05005042const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005043 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005044 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005045 auto it = mWindowHandlesByDisplay.find(displayId);
5046 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005047}
5048
chaviw98318de2021-05-19 16:45:23 -05005049sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005050 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005051 if (windowHandleToken == nullptr) {
5052 return nullptr;
5053 }
5054
Prabir Pradhan16463382023-10-12 23:03:19 +00005055 if (!displayId) {
5056 // Look through all displays.
5057 for (auto& it : mWindowHandlesByDisplay) {
5058 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5059 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5060 if (windowHandle->getToken() == windowHandleToken) {
5061 return windowHandle;
5062 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005065 return nullptr;
5066 }
5067
Prabir Pradhan16463382023-10-12 23:03:19 +00005068 // Only look through the requested display.
5069 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005070 if (windowHandle->getToken() == windowHandleToken) {
5071 return windowHandle;
5072 }
5073 }
5074 return nullptr;
5075}
5076
chaviw98318de2021-05-19 16:45:23 -05005077sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5078 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005079 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005080 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5081 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005082 if (handle->getId() == windowHandle->getId() &&
5083 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005084 if (windowHandle->getInfo()->displayId != it.first) {
5085 ALOGE("Found window %s in display %" PRId32
5086 ", but it should belong to display %" PRId32,
5087 windowHandle->getName().c_str(), it.first,
5088 windowHandle->getInfo()->displayId);
5089 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005090 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005094 return nullptr;
5095}
5096
chaviw98318de2021-05-19 16:45:23 -05005097sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005098 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5099 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100}
5101
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005102ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5103 auto displayInfoIt = mDisplayInfos.find(displayId);
5104 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5105 : kIdentityTransform;
5106}
5107
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005108bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5109 const MotionEntry& motionEntry) const {
5110 const WindowInfo& info = *window->getInfo();
5111
5112 // Skip spy window targets that are not valid for targeted injection.
5113 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005114 return false;
5115 }
5116
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005117 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5118 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5119 return false;
5120 }
5121
5122 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5123 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5124 window->getName().c_str());
5125 return false;
5126 }
5127
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005128 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005129 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005130 ALOGW("Not sending touch to %s because there's no corresponding connection",
5131 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005132 return false;
5133 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005134
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005135 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005136 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005137 return false;
5138 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005139
5140 // Drop events that can't be trusted due to occlusion
5141 const auto [x, y] = resolveTouchedPosition(motionEntry);
5142 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5143 if (!isTouchTrustedLocked(occlusionInfo)) {
5144 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005145 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005146 for (const auto& log : occlusionInfo.debugInfo) {
5147 ALOGD("%s", log.c_str());
5148 }
5149 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005150 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5151 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005152 return false;
5153 }
5154
5155 // Drop touch events if requested by input feature
5156 if (shouldDropInput(motionEntry, window)) {
5157 return false;
5158 }
5159
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005160 // Ignore touches if stylus is down anywhere on screen
5161 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5162 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5163 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5164 return false;
5165 }
5166
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005167 return true;
5168}
5169
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005170void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005171 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5172 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005173 // Remove all handles on a display if there are no windows left.
5174 mWindowHandlesByDisplay.erase(displayId);
5175 return;
5176 }
5177
5178 // Since we compare the pointer of input window handles across window updates, we need
5179 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005180 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5181 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5182 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005183 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005184 }
5185
chaviw98318de2021-05-19 16:45:23 -05005186 std::vector<sp<WindowInfoHandle>> newHandles;
5187 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005188 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005189 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005190 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005191 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005192 const bool canReceiveInput =
5193 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5194 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005195 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005196 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005197 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005198 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005199 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005200 }
5201
5202 if (info->displayId != displayId) {
5203 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5204 handle->getName().c_str(), displayId, info->displayId);
5205 continue;
5206 }
5207
Robert Carredd13602020-04-13 17:24:34 -07005208 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5209 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005210 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005211 oldHandle->updateFrom(handle);
5212 newHandles.push_back(oldHandle);
5213 } else {
5214 newHandles.push_back(handle);
5215 }
5216 }
5217
5218 // Insert or replace
5219 mWindowHandlesByDisplay[displayId] = newHandles;
5220}
5221
Arthur Hungb92218b2018-08-14 12:00:21 +08005222/**
5223 * Called from InputManagerService, update window handle list by displayId that can receive input.
5224 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5225 * If set an empty list, remove all handles from the specific display.
5226 * For focused handle, check if need to change and send a cancel event to previous one.
5227 * For removed handle, check if need to send a cancel event if already in touch.
5228 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005229void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005230 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005231 if (DEBUG_FOCUS) {
5232 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005233 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005234 windowList += iwh->getName() + " ";
5235 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005236 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238
Prabir Pradhand65552b2021-10-07 11:23:50 -07005239 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005240 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005241 const WindowInfo& info = *window->getInfo();
5242
5243 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005244 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005245 if (noInputWindow && window->getToken() != nullptr) {
5246 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5247 window->getName().c_str());
5248 window->releaseChannel();
5249 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005250
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005251 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005252 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5253 !info.inputConfig.test(
5254 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005255 "%s has feature SPY, but is not a trusted overlay.",
5256 window->getName().c_str());
5257
Prabir Pradhand65552b2021-10-07 11:23:50 -07005258 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005259 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5260 !info.inputConfig.test(
5261 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005262 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5263 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005264 }
5265
Arthur Hung72d8dc32020-03-28 00:48:39 +00005266 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005267 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005268 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269
chaviw98318de2021-05-19 16:45:23 -05005270 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005271
chaviw98318de2021-05-19 16:45:23 -05005272 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005273
Vishnu Nairc519ff72021-01-21 08:23:08 -08005274 std::optional<FocusResolver::FocusChanges> changes =
5275 mFocusResolver.setInputWindows(displayId, windowHandles);
5276 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005277 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005280 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5281 mTouchStatesByDisplay.find(displayId);
5282 if (stateIt != mTouchStatesByDisplay.end()) {
5283 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005284 for (size_t i = 0; i < state.windows.size();) {
5285 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005286 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005287 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5288 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005289 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5290 "touched window was removed");
5291 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5292 // Since we are about to drop the touch, cancel the events for the wallpaper as
5293 // well.
5294 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5295 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5296 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5297 if (const auto& ww = state.getWallpaperWindow(); ww) {
5298 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005301 state.windows.erase(state.windows.begin() + i);
5302 } else {
5303 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 }
5305 }
arthurhungb89ccb02020-12-30 16:19:01 +08005306
arthurhung6d4bed92021-03-17 11:59:33 +08005307 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005308 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005309 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005310 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005311 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005312 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5313 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005314 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005315 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005316 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005317
Arthur Hung72d8dc32020-03-28 00:48:39 +00005318 // Release information for windows that are no longer present.
5319 // This ensures that unused input channels are released promptly.
5320 // Otherwise, they might stick around until the window handle is destroyed
5321 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005322 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005323 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005324 if (DEBUG_FOCUS) {
5325 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005326 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005327 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005328 }
chaviw291d88a2019-02-14 10:33:58 -08005329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330}
5331
5332void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005333 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005334 if (DEBUG_FOCUS) {
5335 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5336 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5337 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005338 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005339 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005340 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 } // release lock
5342
5343 // Wake up poll loop since it may need to make new input dispatching choices.
5344 mLooper->wake();
5345}
5346
Vishnu Nair599f1412021-06-21 10:39:58 -07005347void InputDispatcher::setFocusedApplicationLocked(
5348 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5349 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5350 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5351
5352 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5353 return; // This application is already focused. No need to wake up or change anything.
5354 }
5355
5356 // Set the new application handle.
5357 if (inputApplicationHandle != nullptr) {
5358 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5359 } else {
5360 mFocusedApplicationHandlesByDisplay.erase(displayId);
5361 }
5362
5363 // No matter what the old focused application was, stop waiting on it because it is
5364 // no longer focused.
5365 resetNoFocusedWindowTimeoutLocked();
5366}
5367
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005368void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5369 if (interval.count() < 0) {
5370 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5371 }
5372 std::scoped_lock _l(mLock);
5373 mMinTimeBetweenUserActivityPokes = interval;
5374}
5375
Tiger Huang721e26f2018-07-24 22:26:19 +08005376/**
5377 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5378 * the display not specified.
5379 *
5380 * We track any unreleased events for each window. If a window loses the ability to receive the
5381 * released event, we will send a cancel event to it. So when the focused display is changed, we
5382 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5383 * display. The display-specified events won't be affected.
5384 */
5385void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005386 if (DEBUG_FOCUS) {
5387 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5388 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005389 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005390 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005391
5392 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005393 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005394 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005395 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005396 const auto windowHandle =
5397 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5398 if (windowHandle == nullptr) {
5399 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005400 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005401 CancelationOptions
5402 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5403 "The display which contains this window no longer has focus.");
5404 options.displayId = ADISPLAY_ID_NONE;
5405 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005406 }
5407 mFocusedDisplayId = displayId;
5408
Chris Ye3c2d6f52020-08-09 10:39:48 -07005409 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005410 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005411 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005412
Vishnu Nairad321cd2020-08-20 16:40:21 -07005413 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005414 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005415 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005416 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005417 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005418 }
5419 }
5420 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005421 } // release lock
5422
5423 // Wake up poll loop since it may need to make new input dispatching choices.
5424 mLooper->wake();
5425}
5426
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005428 if (DEBUG_FOCUS) {
5429 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431
5432 bool changed;
5433 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005434 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
5436 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5437 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005438 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440
5441 if (mDispatchEnabled && !enabled) {
5442 resetAndDropEverythingLocked("dispatcher is being disabled");
5443 }
5444
5445 mDispatchEnabled = enabled;
5446 mDispatchFrozen = frozen;
5447 changed = true;
5448 } else {
5449 changed = false;
5450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 } // release lock
5452
5453 if (changed) {
5454 // Wake up poll loop since it may need to make new input dispatching choices.
5455 mLooper->wake();
5456 }
5457}
5458
5459void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005460 if (DEBUG_FOCUS) {
5461 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
5464 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005465 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466
5467 if (mInputFilterEnabled == enabled) {
5468 return;
5469 }
5470
5471 mInputFilterEnabled = enabled;
5472 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5473 } // release lock
5474
5475 // Wake up poll loop since there might be work to do to drop everything.
5476 mLooper->wake();
5477}
5478
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005479bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005480 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005481 bool needWake = false;
5482 {
5483 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005484 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005485 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005486 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005487 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5488 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005489 mTouchModePerDisplay.count(displayId) == 0
5490 ? "not set"
5491 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5492
Antonio Kantek15beb512022-06-13 22:35:41 +00005493 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5494 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005495 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005496 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005497 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005498 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5499 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005500 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005501 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005502 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005503 return false;
5504 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005505 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005506 mTouchModePerDisplay[displayId] = inTouchMode;
5507 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5508 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005509 needWake = enqueueInboundEventLocked(std::move(entry));
5510 } // release lock
5511
5512 if (needWake) {
5513 mLooper->wake();
5514 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005515 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005516}
5517
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005518bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005519 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5520 if (focusedToken == nullptr) {
5521 return false;
5522 }
5523 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5524 return isWindowOwnedBy(windowHandle, pid, uid);
5525}
5526
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005527bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005528 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5529 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5530 const sp<WindowInfoHandle> windowHandle =
5531 getWindowHandleLocked(connectionToken);
5532 return isWindowOwnedBy(windowHandle, pid, uid);
5533 }) != mInteractionConnectionTokens.end();
5534}
5535
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005536void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5537 if (opacity < 0 || opacity > 1) {
5538 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5539 return;
5540 }
5541
5542 std::scoped_lock lock(mLock);
5543 mMaximumObscuringOpacityForTouch = opacity;
5544}
5545
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005546std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5547InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005548 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5549 for (TouchedWindow& w : state.windows) {
5550 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005551 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005552 }
5553 }
5554 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005555 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005556}
5557
Prabir Pradhan367f3432024-02-13 23:05:58 +00005558bool InputDispatcher::transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5559 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005560 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005561 if (DEBUG_FOCUS) {
5562 ALOGD("Trivial transfer to same window.");
5563 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005564 return true;
5565 }
5566
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005568 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005571 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005572
Arthur Hungabbb9d82021-09-01 14:52:30 +00005573 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005574 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 return false;
5576 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005577 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5578 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005579 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5580 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005581 return false;
5582 }
5583 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005584
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005585 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5586 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5587 if (!toWindowHandle) {
5588 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005589 return false;
5590 }
5591
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005592 if (DEBUG_FOCUS) {
Prabir Pradhan367f3432024-02-13 23:05:58 +00005593 ALOGD("%s: fromWindowHandle=%s, toWindowHandle=%s", __func__,
Arthur Hungabbb9d82021-09-01 14:52:30 +00005594 touchedWindow->windowHandle->getName().c_str(),
5595 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 }
5597
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005599 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005600 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005601 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
Arthur Hungabbb9d82021-09-01 14:52:30 +00005603 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005604 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005605 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005606 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005607 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005608 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005609 }
Prabir Pradhan65455c72024-02-13 21:46:41 +00005610 // Transferring touch focus using this API should not effect the focused window.
5611 newTargetFlags |= InputTarget::Flags::NO_FOCUS_CHANGE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005612 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005613 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614
Arthur Hungabbb9d82021-09-01 14:52:30 +00005615 // Store the dragging window.
5616 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005617 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005618 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5619 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005620 return false;
5621 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005622 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005623 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005624 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 }
5626
Arthur Hungabbb9d82021-09-01 14:52:30 +00005627 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005628 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5629 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005630 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005631 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005632 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5633 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005634 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005635 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5636 newTargetFlags);
5637
5638 // Check if the wallpaper window should deliver the corresponding event.
5639 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005640 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 } // release lock
5643
5644 // Wake up poll loop since it may need to make new input dispatching choices.
5645 mLooper->wake();
5646 return true;
5647}
5648
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005649/**
5650 * Get the touched foreground window on the given display.
5651 * Return null if there are no windows touched on that display, or if more than one foreground
5652 * window is being touched.
5653 */
5654sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5655 auto stateIt = mTouchStatesByDisplay.find(displayId);
5656 if (stateIt == mTouchStatesByDisplay.end()) {
5657 ALOGI("No touch state on display %" PRId32, displayId);
5658 return nullptr;
5659 }
5660
5661 const TouchState& state = stateIt->second;
5662 sp<WindowInfoHandle> touchedForegroundWindow;
5663 // If multiple foreground windows are touched, return nullptr
5664 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005665 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005666 if (touchedForegroundWindow != nullptr) {
5667 ALOGI("Two or more foreground windows: %s and %s",
5668 touchedForegroundWindow->getName().c_str(),
5669 window.windowHandle->getName().c_str());
5670 return nullptr;
5671 }
5672 touchedForegroundWindow = window.windowHandle;
5673 }
5674 }
5675 return touchedForegroundWindow;
5676}
5677
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005678// Binder call
Prabir Pradhan367f3432024-02-13 23:05:58 +00005679bool InputDispatcher::transferTouchOnDisplay(const sp<IBinder>& destChannelToken,
5680 int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005681 sp<IBinder> fromToken;
5682 { // acquire lock
5683 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005684 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005685 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005686 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5687 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005688 return false;
5689 }
5690
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005691 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5692 if (from == nullptr) {
5693 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5694 return false;
5695 }
5696
5697 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005698 } // release lock
5699
Prabir Pradhan367f3432024-02-13 23:05:58 +00005700 return transferTouchGesture(fromToken, destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005701}
5702
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005704 if (DEBUG_FOCUS) {
5705 ALOGD("Resetting and dropping all events (%s).", reason);
5706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707
Michael Wrightfb04fd52022-11-24 22:31:11 +00005708 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 synthesizeCancelationEventsForAllConnectionsLocked(options);
5710
5711 resetKeyRepeatLocked();
5712 releasePendingEventLocked();
5713 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005714 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005716 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005717 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718}
5719
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005720void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005721 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 dumpDispatchStateLocked(dump);
5723
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005724 std::istringstream stream(dump);
5725 std::string line;
5726
5727 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005728 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
5730}
5731
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005732std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005733 std::string dump;
5734
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005735 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5736 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005737
5738 std::string windowName = "None";
5739 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005740 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005741 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5742 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5743 : "token has capture without window";
5744 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005745 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005746
5747 return dump;
5748}
5749
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005750void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005751 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5752 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5753 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005754 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755
Tiger Huang721e26f2018-07-24 22:26:19 +08005756 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5757 dump += StringPrintf(INDENT "FocusedApplications:\n");
5758 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5759 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005760 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005761 const std::chrono::duration timeout =
5762 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005763 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005764 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005765 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005768 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005770
Vishnu Nairc519ff72021-01-21 08:23:08 -08005771 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005772 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005774 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005776 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005777 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5778 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783
arthurhung6d4bed92021-03-17 11:59:33 +08005784 if (mDragState) {
5785 dump += StringPrintf(INDENT "DragState:\n");
5786 mDragState->dump(dump, INDENT2);
5787 }
5788
Arthur Hungb92218b2018-08-14 12:00:21 +08005789 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005790 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5791 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5792 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5793 const auto& displayInfo = it->second;
5794 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5795 displayInfo.logicalHeight);
5796 displayInfo.transform.dump(dump, "transform", INDENT4);
5797 } else {
5798 dump += INDENT2 "No DisplayInfo found!\n";
5799 }
5800
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005801 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005802 dump += INDENT2 "Windows:\n";
5803 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005804 dump += StringPrintf(INDENT3 "%zu: %s", i,
5805 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005806 }
5807 } else {
5808 dump += INDENT2 "Windows: <none>\n";
5809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 }
5811 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005812 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 }
5814
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005815 if (!mGlobalMonitorsByDisplay.empty()) {
5816 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5817 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005818 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005821 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822 }
5823
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005824 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825
5826 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005827 if (!mRecentQueue.empty()) {
5828 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005829 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005830 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005831 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005832 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
5834 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005835 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 }
5837
5838 // Dump event currently being dispatched.
5839 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005840 dump += INDENT "PendingEvent:\n";
5841 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005842 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005843 dump += StringPrintf(", age=%" PRId64 "ms\n",
5844 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005846 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 }
5848
5849 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005850 if (!mInboundQueue.empty()) {
5851 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005852 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005853 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005854 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005855 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 }
5857 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005858 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859 }
5860
Prabir Pradhancef936d2021-07-21 16:17:52 +00005861 if (!mCommandQueue.empty()) {
5862 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5863 } else {
5864 dump += INDENT "CommandQueue: <empty>\n";
5865 }
5866
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005867 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005868 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005869 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005870 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005871 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005872 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005873 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005874 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005875 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005877 if (!connection->outboundQueue.empty()) {
5878 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5879 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005880 dump += dumpQueue(connection->outboundQueue, currentTime);
5881
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005883 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 }
5885
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005886 if (!connection->waitQueue.empty()) {
5887 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5888 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005889 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005891 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005893 std::string inputStateDump = streamableToString(connection->inputState);
5894 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005895 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005896 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 }
5899 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005900 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 }
5902
Antonio Kantek15beb512022-06-13 22:35:41 +00005903 if (!mTouchModePerDisplay.empty()) {
5904 dump += INDENT "TouchModePerDisplay:\n";
5905 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5906 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5907 std::to_string(touchMode).c_str());
5908 }
5909 } else {
5910 dump += INDENT "TouchModePerDisplay: <none>\n";
5911 }
5912
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005913 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005914 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5915 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5916 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005917 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005918 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005919 dump += INDENT "InputTracer: ";
5920 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921}
5922
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005923void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005924 const size_t numMonitors = monitors.size();
5925 for (size_t i = 0; i < numMonitors; i++) {
5926 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005927 const std::shared_ptr<Connection>& connection = monitor.connection;
5928 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005929 dump += "\n";
5930 }
5931}
5932
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005933class LooperEventCallback : public LooperCallback {
5934public:
5935 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5936 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5937
5938private:
5939 std::function<int(int events)> mCallback;
5940};
5941
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005942Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005943 if (DEBUG_CHANNEL_CREATION) {
5944 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005947 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005948 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005949 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005950
5951 if (result) {
5952 return base::Error(result) << "Failed to open input channel pair with name " << name;
5953 }
5954
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005956 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005957 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005958 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005959 std::shared_ptr<Connection> connection =
5960 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5961 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005963 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5964 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005965 ALOGE("Created a new connection, but the token %p is already known", token.get());
5966 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005967
5968 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5969 this, std::placeholders::_1, token);
5970
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005971 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005972 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 } // release lock
5974
5975 // Wake the looper because some connections have changed.
5976 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005977 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978}
5979
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005980Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005981 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005982 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005983 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005984 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005985 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005986 if (result) {
5987 return base::Error(result) << "Failed to open input channel pair with name " << name;
5988 }
5989
Michael Wright3dd60e22019-03-27 22:06:44 +00005990 { // acquire lock
5991 std::scoped_lock _l(mLock);
5992
5993 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005994 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5995 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005996 }
5997
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005998 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005999 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006000 std::shared_ptr<Connection> connection =
6001 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
6002 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006003
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006004 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6005 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006006 ALOGE("Created a new connection, but the token %p is already known", token.get());
6007 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006008
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006009 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6010 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006011
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006012 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006013
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006014 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006015 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006016 }
Garfield Tan15601662020-09-22 15:32:38 -07006017
Michael Wright3dd60e22019-03-27 22:06:44 +00006018 // Wake the looper because some connections have changed.
6019 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006020 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006021}
6022
Garfield Tan15601662020-09-22 15:32:38 -07006023status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026
Harry Cutts33476232023-01-30 19:57:29 +00006027 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 if (status) {
6029 return status;
6030 }
6031 } // release lock
6032
6033 // Wake the poll loop because removing the connection may have changed the current
6034 // synchronization state.
6035 mLooper->wake();
6036 return OK;
6037}
6038
Garfield Tan15601662020-09-22 15:32:38 -07006039status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6040 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006041 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006042 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006043 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 return BAD_VALUE;
6045 }
6046
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006047 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006048
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006050 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 }
6052
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006053 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054
6055 nsecs_t currentTime = now();
6056 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6057
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006058 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059 return OK;
6060}
6061
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006062void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006063 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6064 auto& [displayId, monitors] = *it;
6065 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006066 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006067 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006068
Michael Wright3dd60e22019-03-27 22:06:44 +00006069 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006071 } else {
6072 ++it;
6073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074 }
6075}
6076
Michael Wright3dd60e22019-03-27 22:06:44 +00006077status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006078 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006079 return pilferPointersLocked(token);
6080}
Michael Wright3dd60e22019-03-27 22:06:44 +00006081
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006082status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006083 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6084 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006085 LOG(WARNING)
6086 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006087 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006088 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006089
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006090 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006091 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006092 LOG(WARNING)
6093 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6094 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006095 return BAD_VALUE;
6096 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006097 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006098 if (deviceIds.empty()) {
6099 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006100 return BAD_VALUE;
6101 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006102
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006103 for (const DeviceId deviceId : deviceIds) {
6104 TouchState& state = *statePtr;
6105 TouchedWindow& window = *windowPtr;
6106 // Send cancel events to all the input channels we're stealing from.
6107 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6108 "input channel stole pointer stream");
6109 options.deviceId = deviceId;
6110 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006111 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6112 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006113 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006114
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006115 std::string canceledWindows;
6116 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006117 if (w.windowHandle->getToken() != token) {
6118 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006119 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006120 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006121 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006122 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006123 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006124 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006125 << " is stealing input gesture for device " << deviceId << " from "
6126 << canceledWindows;
6127
6128 // Prevent the gesture from being sent to any other windows.
6129 // This only blocks relevant pointers to be sent to other windows
6130 window.addPilferingPointers(deviceId, pointerIds);
6131
6132 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006133 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006134 return OK;
6135}
6136
Prabir Pradhan99987712020-11-10 18:43:05 -08006137void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6138 { // acquire lock
6139 std::scoped_lock _l(mLock);
6140 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006141 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006142 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6143 windowHandle != nullptr ? windowHandle->getName().c_str()
6144 : "token without window");
6145 }
6146
Vishnu Nairc519ff72021-01-21 08:23:08 -08006147 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006148 if (focusedToken != windowToken) {
6149 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6150 enabled ? "enable" : "disable");
6151 return;
6152 }
6153
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006154 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006155 ALOGW("Ignoring request to %s Pointer Capture: "
6156 "window has %s requested pointer capture.",
6157 enabled ? "enable" : "disable", enabled ? "already" : "not");
6158 return;
6159 }
6160
Christine Franksb768bb42021-11-29 12:11:31 -08006161 if (enabled) {
6162 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6163 mIneligibleDisplaysForPointerCapture.end(),
6164 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6165 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6166 return;
6167 }
6168 }
6169
Prabir Pradhan99987712020-11-10 18:43:05 -08006170 setPointerCaptureLocked(enabled);
6171 } // release lock
6172
6173 // Wake the thread to process command entries.
6174 mLooper->wake();
6175}
6176
Christine Franksb768bb42021-11-29 12:11:31 -08006177void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6178 { // acquire lock
6179 std::scoped_lock _l(mLock);
6180 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6181 if (!isEligible) {
6182 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6183 }
6184 } // release lock
6185}
6186
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006187std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006188 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006189 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006190 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006191 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006192 }
6193 }
6194 }
6195 return std::nullopt;
6196}
6197
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006198std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6199 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006200 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006201 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006202 }
6203
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006204 for (const auto& [token, connection] : mConnectionsByToken) {
6205 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006206 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207 }
6208 }
Robert Carr4e670e52018-08-15 13:26:12 -07006209
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006210 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211}
6212
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006213std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006214 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006215 if (connection == nullptr) {
6216 return "<nullptr>";
6217 }
6218 return connection->getInputChannelName();
6219}
6220
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006221void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006222 mAnrTracker.eraseToken(connection->getToken());
6223 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006224}
6225
Prabir Pradhancef936d2021-07-21 16:17:52 +00006226void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006227 const std::shared_ptr<Connection>& connection,
6228 uint32_t seq, bool handled,
6229 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006231 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006232
6233 { // Start critical section
6234 auto dispatchEntryIt =
6235 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6236 [seq](auto& e) { return e->seq == seq; });
6237 if (dispatchEntryIt == connection->waitQueue.end()) {
6238 return;
6239 }
6240
6241 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6242
6243 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6244 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006245 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006246 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6247 }
6248 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006249 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006250 dispatchEntry.deliveryTime, consumeTime, finishTime);
6251 }
6252
6253 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006254 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6255 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006256 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006257 }
6258 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006259
6260 // Dequeue the event and start the next cycle.
6261 // Because the lock might have been released, it is possible that the
6262 // contents of the wait queue to have been drained, so we need to double-check
6263 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006264 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6265 [seq](auto& e) { return e->seq == seq; });
6266 if (entryIt != connection->waitQueue.end()) {
6267 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6268 connection->waitQueue.erase(entryIt);
6269
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006270 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006271 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6272 if (!connection->responsive) {
6273 connection->responsive = isConnectionResponsive(*connection);
6274 if (connection->responsive) {
6275 // The connection was unresponsive, and now it's responsive.
6276 processConnectionResponsiveLocked(*connection);
6277 }
6278 }
6279 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006280 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006281 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6282 // Only dispatch fallbacks if there is a window for the connection.
6283 if (windowHandle != nullptr) {
6284 const auto inputTarget =
6285 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6286 dispatchEntry->targetFlags,
6287 fallbackKeyEntry->downTime);
6288 if (inputTarget.has_value()) {
6289 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6290 *inputTarget);
6291 }
6292 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006294 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 }
6296
6297 // Start the next dispatch cycle for this connection.
6298 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299}
6300
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6302 const sp<IBinder>& newToken) {
6303 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6304 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006305 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006306 };
6307 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308}
6309
Prabir Pradhancef936d2021-07-21 16:17:52 +00006310void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6311 auto command = [this, token, x, y]() REQUIRES(mLock) {
6312 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006313 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006314 };
6315 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006316}
6317
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006318void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006319 if (connection == nullptr) {
6320 LOG_ALWAYS_FATAL("Caller must check for nullness");
6321 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006322 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6323 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006324 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006325 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006326 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006327 return;
6328 }
6329 /**
6330 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6331 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6332 * has changed. This could cause newer entries to time out before the already dispatched
6333 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6334 * processes the events linearly. So providing information about the oldest entry seems to be
6335 * most useful.
6336 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006337 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6338 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006339 std::string reason =
6340 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006341 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006342 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006343 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006344 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006345 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006347 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6348
6349 // Stop waking up for events on this connection, it is already unresponsive
6350 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006351}
6352
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006353void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6354 std::string reason =
6355 StringPrintf("%s does not have a focused window", application->getName().c_str());
6356 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006357
Yabin Cui8eb9c552023-06-08 18:05:07 +00006358 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006359 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006360 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006361 };
6362 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006363}
6364
chaviw98318de2021-05-19 16:45:23 -05006365void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006366 const std::string& reason) {
6367 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6368 updateLastAnrStateLocked(windowLabel, reason);
6369}
6370
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006371void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6372 const std::string& reason) {
6373 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006374 updateLastAnrStateLocked(windowLabel, reason);
6375}
6376
6377void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6378 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006380 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381 struct tm tm;
6382 localtime_r(&t, &tm);
6383 char timestr[64];
6384 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006385 mLastAnrState.clear();
6386 mLastAnrState += INDENT "ANR:\n";
6387 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006388 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6389 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006390 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391}
6392
Prabir Pradhancef936d2021-07-21 16:17:52 +00006393void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006394 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006395 const KeyEvent event = createKeyEvent(entry);
6396 nsecs_t delay = 0;
6397 { // release lock
6398 scoped_unlock unlock(mLock);
6399 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006400 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006401 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6402 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6403 std::to_string(t.duration().count()).c_str());
6404 }
6405 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406
6407 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006408 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006409 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006410 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006411 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006412 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006413 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415}
6416
Prabir Pradhancef936d2021-07-21 16:17:52 +00006417void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006418 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006419 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006420 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006421 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006422 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006423 };
6424 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006425}
6426
Prabir Pradhanedd96402022-02-15 01:46:16 -08006427void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006428 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006429 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006430 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006431 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006432 };
6433 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006434}
6435
6436/**
6437 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6438 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6439 * command entry to the command queue.
6440 */
6441void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6442 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006443 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006444 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006445 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006446 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006447 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006448 pid = findMonitorPidByTokenLocked(connectionToken);
6449 } else {
6450 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006451 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006452 reason.c_str());
6453 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6454 if (handle != nullptr) {
6455 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006456 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006457 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006458 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006459}
6460
6461/**
6462 * Tell the policy that a connection has become responsive so that it can stop ANR.
6463 */
6464void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006465 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006466 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006467 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006468 pid = findMonitorPidByTokenLocked(connectionToken);
6469 } else {
6470 // The connection is a window
6471 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6472 if (handle != nullptr) {
6473 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006474 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006475 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006476 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006477}
6478
Prabir Pradhan24047542023-11-02 17:14:59 +00006479std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006480 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006481 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006482 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006483 if (!handled) {
6484 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006485 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006486 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006487 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006489
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 // Get the fallback key state.
6491 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006492 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006493 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006494 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006495 connection->inputState.removeFallbackKey(originalKeyCode);
6496 }
6497
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006498 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 // If the application handles the original key for which we previously
6500 // generated a fallback or if the window is not a foreground window,
6501 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006502 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006503 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006504 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6505 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6506 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6507 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6508 keyEntry.policyFlags);
6509 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006510 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512
6513 mLock.unlock();
6514
Prabir Pradhana41d2442023-04-20 21:30:40 +00006515 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006516 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6517 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006518 unhandledKeyFallback) {
6519 event = *unhandledKeyFallback;
6520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521
6522 mLock.lock();
6523
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006524 // Cancel the fallback key, but only if we still have a window for the channel.
6525 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006526 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006527 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6528 if (windowHandle != nullptr) {
6529 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6530 "application handled the original non-fallback key "
6531 "or is no longer a foreground target, "
6532 "canceling previously dispatched fallback key");
6533 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006534 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006536 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006537 connection->inputState.removeFallbackKey(originalKeyCode);
6538 }
6539 } else {
6540 // If the application did not handle a non-fallback key, first check
6541 // that we are in a good state to perform unhandled key event processing
6542 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006543 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006544 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006545 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6546 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6547 "since this is not an initial down. "
6548 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6549 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6550 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006551 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006554 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006555 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6556 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6557 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6558 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6559 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006560 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006561
6562 mLock.unlock();
6563
Prabir Pradhana41d2442023-04-20 21:30:40 +00006564 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006565 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6566 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006567 fb) {
6568 fallback = true;
6569 event = *fb;
6570 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006571
6572 mLock.lock();
6573
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006574 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006575 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006576 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006577 }
6578
6579 // Latch the fallback keycode for this key on an initial down.
6580 // The fallback keycode cannot change at any other point in the lifecycle.
6581 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006583 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006584 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006585 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006586 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006587 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006588 }
6589
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006590 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006591
6592 // Cancel the fallback key if the policy decides not to send it anymore.
6593 // We will continue to dispatch the key to the policy but we will no
6594 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006595 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6596 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006597 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6598 if (fallback) {
6599 ALOGD("Unhandled key event: Policy requested to send key %d"
6600 "as a fallback for %d, but on the DOWN it had requested "
6601 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006602 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006603 } else {
6604 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6605 "but on the DOWN it had requested to send %d. "
6606 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006607 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006608 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006609 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006610
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006611 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6612 if (windowHandle != nullptr) {
6613 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6614 "canceling fallback, policy no longer desires it");
6615 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006616 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006617 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618
6619 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006620 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006621 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006622 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006623 }
6624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006626 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6627 {
6628 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006629 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006630 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006631 for (const auto& [key, value] : fallbackKeys) {
6632 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006633 }
6634 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6635 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006636 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006637 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006638
6639 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006640 // Return the fallback key that we want dispatched to the channel.
6641 std::unique_ptr<KeyEntry> newEntry =
6642 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6643 event.getEventTime(), event.getDeviceId(),
6644 event.getSource(), event.getDisplayId(),
6645 keyEntry.policyFlags, keyEntry.action,
6646 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6647 *fallbackKeyCode, event.getScanCode(),
6648 event.getMetaState(), event.getRepeatCount(),
6649 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006650 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6651 ALOGD("Unhandled key event: Dispatching fallback key. "
6652 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006653 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006654 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006655 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006656 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006657 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6658 ALOGD("Unhandled key event: No fallback key.");
6659 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006660
6661 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006662 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663 }
6664 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006665 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666}
6667
Michael Wrightd02c5b62014-02-10 15:10:22 -08006668void InputDispatcher::traceInboundQueueLengthLocked() {
6669 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006670 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006671 }
6672}
6673
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006674void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675 if (ATRACE_ENABLED()) {
6676 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006677 snprintf(counterName, sizeof(counterName), "oq:%s",
6678 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006679 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006680 }
6681}
6682
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006683void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006684 if (ATRACE_ENABLED()) {
6685 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006686 snprintf(counterName, sizeof(counterName), "wq:%s",
6687 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006688 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006689 }
6690}
6691
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006692void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006693 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006694
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006695 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006696 dumpDispatchStateLocked(dump);
6697
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006698 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006699 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006700 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006701 }
6702}
6703
6704void InputDispatcher::monitor() {
6705 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006706 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006707 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006708 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006709}
6710
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006711/**
6712 * Wake up the dispatcher and wait until it processes all events and commands.
6713 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6714 * this method can be safely called from any thread, as long as you've ensured that
6715 * the work you are interested in completing has already been queued.
6716 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006717bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006718 /**
6719 * Timeout should represent the longest possible time that a device might spend processing
6720 * events and commands.
6721 */
6722 constexpr std::chrono::duration TIMEOUT = 100ms;
6723 std::unique_lock lock(mLock);
6724 mLooper->wake();
6725 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6726 return result == std::cv_status::no_timeout;
6727}
6728
Vishnu Naire798b472020-07-23 13:52:21 -07006729/**
6730 * Sets focus to the window identified by the token. This must be called
6731 * after updating any input window handles.
6732 *
6733 * Params:
6734 * request.token - input channel token used to identify the window that should gain focus.
6735 * request.focusedToken - the token that the caller expects currently to be focused. If the
6736 * specified token does not match the currently focused window, this request will be dropped.
6737 * If the specified focused token matches the currently focused window, the call will succeed.
6738 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6739 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6740 * when requesting the focus change. This determines which request gets
6741 * precedence if there is a focus change request from another source such as pointer down.
6742 */
Vishnu Nair958da932020-08-21 17:12:37 -07006743void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6744 { // acquire lock
6745 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006746 std::optional<FocusResolver::FocusChanges> changes =
6747 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6748 if (changes) {
6749 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006750 }
6751 } // release lock
6752 // Wake up poll loop since it may need to make new input dispatching choices.
6753 mLooper->wake();
6754}
6755
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006756void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6757 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006758 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006759 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6760 ? removedFocusedWindowHandle
6761 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6762 if (resolvedWindow == nullptr) {
6763 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006764 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006765 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6766 "focus left window");
6767 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6768 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006769 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006770 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006771 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006772 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006773 }
6774
Prabir Pradhan99987712020-11-10 18:43:05 -08006775 // If a window has pointer capture, then it must have focus. We need to ensure that this
6776 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6777 // If the window loses focus before it loses pointer capture, then the window can be in a state
6778 // where it has pointer capture but not focus, violating the contract. Therefore we must
6779 // dispatch the pointer capture event before the focus event. Since focus events are added to
6780 // the front of the queue (above), we add the pointer capture event to the front of the queue
6781 // after the focus events are added. This ensures the pointer capture event ends up at the
6782 // front.
6783 disablePointerCaptureForcedLocked();
6784
Vishnu Nairc519ff72021-01-21 08:23:08 -08006785 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006786 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006787 }
6788}
Vishnu Nair958da932020-08-21 17:12:37 -07006789
Prabir Pradhan99987712020-11-10 18:43:05 -08006790void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006791 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006792 return;
6793 }
6794
6795 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6796
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006797 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006798 setPointerCaptureLocked(false);
6799 }
6800
6801 if (!mWindowTokenWithPointerCapture) {
6802 // No need to send capture changes because no window has capture.
6803 return;
6804 }
6805
6806 if (mPendingEvent != nullptr) {
6807 // Move the pending event to the front of the queue. This will give the chance
6808 // for the pending event to be dropped if it is a captured event.
6809 mInboundQueue.push_front(mPendingEvent);
6810 mPendingEvent = nullptr;
6811 }
6812
6813 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006814 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006815 mInboundQueue.push_front(std::move(entry));
6816}
6817
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006818void InputDispatcher::setPointerCaptureLocked(bool enable) {
6819 mCurrentPointerCaptureRequest.enable = enable;
6820 mCurrentPointerCaptureRequest.seq++;
6821 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006822 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006823 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006824 };
6825 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006826}
6827
Vishnu Nair599f1412021-06-21 10:39:58 -07006828void InputDispatcher::displayRemoved(int32_t displayId) {
6829 { // acquire lock
6830 std::scoped_lock _l(mLock);
6831 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006832 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006833 setFocusedApplicationLocked(displayId, nullptr);
6834 // Call focus resolver to clean up stale requests. This must be called after input windows
6835 // have been removed for the removed display.
6836 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006837 // Reset pointer capture eligibility, regardless of previous state.
6838 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006839 // Remove the associated touch mode state.
6840 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006841 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006842 } // release lock
6843
6844 // Wake up poll loop since it may need to make new input dispatching choices.
6845 mLooper->wake();
6846}
6847
Patrick Williamsd828f302023-04-28 17:52:08 -05006848void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006849 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6850 {
6851 // acquire lock
6852 std::scoped_lock _l(mLock);
6853 logDispatchStateLocked();
6854 }
6855 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6856 result.error().message().c_str());
6857 };
chaviw15fab6f2021-06-07 14:15:52 -05006858 // The listener sends the windows as a flattened array. Separate the windows by display for
6859 // more convenient parsing.
6860 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006861 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006862 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006863 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006864 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006865
6866 { // acquire lock
6867 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006868
6869 // Ensure that we have an entry created for all existing displays so that if a displayId has
6870 // no windows, we can tell that the windows were removed from the display.
6871 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6872 handlesPerDisplay[displayId];
6873 }
6874
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006875 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006876 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006877 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6878 }
6879
6880 for (const auto& [displayId, handles] : handlesPerDisplay) {
6881 setInputWindowsLocked(handles, displayId);
6882 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006883
6884 if (update.vsyncId < mWindowInfosVsyncId) {
6885 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6886 ", current update vsync id: %" PRId64,
6887 mWindowInfosVsyncId, update.vsyncId);
6888 }
6889 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006890 }
6891 // Wake up poll loop since it may need to make new input dispatching choices.
6892 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006893}
6894
Vishnu Nair062a8672021-09-03 16:07:44 -07006895bool InputDispatcher::shouldDropInput(
6896 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006897 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6898 (windowHandle->getInfo()->inputConfig.test(
6899 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006900 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006901 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6902 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006903 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006904 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006905 windowHandle->getInfo()->displayId);
6906 return true;
6907 }
6908 return false;
6909}
6910
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006911void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006912 const gui::WindowInfosUpdate& update) {
6913 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006914}
6915
Arthur Hungdfd528e2021-12-08 13:23:04 +00006916void InputDispatcher::cancelCurrentTouch() {
6917 {
6918 std::scoped_lock _l(mLock);
6919 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006920 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006921 "cancel current touch");
6922 synthesizeCancelationEventsForAllConnectionsLocked(options);
6923
6924 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006925 }
6926 // Wake up poll loop since there might be work to do.
6927 mLooper->wake();
6928}
6929
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006930void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6931 std::scoped_lock _l(mLock);
6932 mMonitorDispatchingTimeout = timeout;
6933}
6934
Arthur Hungc539dbb2022-12-08 07:45:36 +00006935void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6936 const sp<WindowInfoHandle>& oldWindowHandle,
6937 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006938 TouchState& state, int32_t deviceId,
6939 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006940 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006941 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006942 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6943 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6944 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6945 newWindowHandle->getInfo()->inputConfig.test(
6946 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6947 const sp<WindowInfoHandle> oldWallpaper =
6948 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6949 const sp<WindowInfoHandle> newWallpaper =
6950 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6951 if (oldWallpaper == newWallpaper) {
6952 return;
6953 }
6954
6955 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006956 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006957 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006958 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006959 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006960 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006961 }
6962
6963 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006964 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6965 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006966 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006967 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006968 }
6969}
6970
6971void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6972 ftl::Flags<InputTarget::Flags> newTargetFlags,
6973 const sp<WindowInfoHandle> fromWindowHandle,
6974 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006975 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006976 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006977 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6978 fromWindowHandle->getInfo()->inputConfig.test(
6979 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6980 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6981 toWindowHandle->getInfo()->inputConfig.test(
6982 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6983
6984 const sp<WindowInfoHandle> oldWallpaper =
6985 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6986 const sp<WindowInfoHandle> newWallpaper =
6987 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6988 if (oldWallpaper == newWallpaper) {
6989 return;
6990 }
6991
6992 if (oldWallpaper != nullptr) {
6993 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6994 "transferring touch focus to another window");
6995 state.removeWindowByToken(oldWallpaper->getToken());
6996 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6997 }
6998
6999 if (newWallpaper != nullptr) {
7000 nsecs_t downTimeInTarget = now();
Prabir Pradhan65455c72024-02-13 21:46:41 +00007001 ftl::Flags<InputTarget::Flags> wallpaperFlags = newTargetFlags;
7002 wallpaperFlags |= oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00007003 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
7004 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00007005 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007006 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007007 std::shared_ptr<Connection> wallpaperConnection =
7008 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007009 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007010 std::shared_ptr<Connection> toConnection =
7011 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007012 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7013 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7014 wallpaperFlags);
7015 }
7016 }
7017}
7018
7019sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7020 const sp<WindowInfoHandle>& windowHandle) const {
7021 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7022 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7023 bool foundWindow = false;
7024 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7025 if (!foundWindow && otherHandle != windowHandle) {
7026 continue;
7027 }
7028 if (windowHandle == otherHandle) {
7029 foundWindow = true;
7030 continue;
7031 }
7032
7033 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7034 return otherHandle;
7035 }
7036 }
7037 return nullptr;
7038}
7039
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007040void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7041 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007042 std::scoped_lock _l(mLock);
7043
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007044 mConfig.keyRepeatTimeout = timeout.count();
7045 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007046}
7047
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007048bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7049 DeviceId deviceId, int32_t pointerId) {
7050 std::scoped_lock _l(mLock);
7051 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7052 if (touchStateIt == mTouchStatesByDisplay.end()) {
7053 return false;
7054 }
7055 for (const TouchedWindow& window : touchStateIt->second.windows) {
7056 if (window.windowHandle->getToken() == token &&
7057 (window.hasTouchingPointer(deviceId, pointerId) ||
7058 window.hasHoveringPointer(deviceId, pointerId))) {
7059 return true;
7060 }
7061 }
7062 return false;
7063}
7064
Garfield Tane84e6f92019-08-29 17:28:41 -07007065} // namespace android::inputdispatcher