blob: 0ab6af757ddb425cee2cd310f7d07871929def26 [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 }
3425
3426 dispatchEntry->resolvedFlags = resolvedFlags;
3427 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003428 std::optional<std::vector<PointerProperties>> usingProperties;
3429 std::optional<std::vector<PointerCoords>> usingCoords;
3430 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3431 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3432 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3433 // the dispatcher, and therefore the coordinates of this event are currently
3434 // incorrect. These events should use the coordinates of the last dispatched
3435 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3436 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3437 std::optional<std::pair<std::vector<PointerProperties>,
3438 std::vector<PointerCoords>>>
3439 pointerInfo =
3440 connection->inputState.getPointersOfLastEvent(motionEntry,
3441 hovering);
3442 if (pointerInfo) {
3443 usingProperties = pointerInfo->first;
3444 usingCoords = pointerInfo->second;
3445 }
3446 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003447 // Generate a new MotionEntry with a new eventId using the resolved action and
3448 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003449 resolvedMotion = std::make_shared<
3450 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3451 motionEntry.eventTime, motionEntry.deviceId,
3452 motionEntry.source, motionEntry.displayId,
3453 motionEntry.policyFlags, resolvedAction,
3454 motionEntry.actionButton, resolvedFlags,
3455 motionEntry.metaState, motionEntry.buttonState,
3456 motionEntry.classification, motionEntry.edgeFlags,
3457 motionEntry.xPrecision, motionEntry.yPrecision,
3458 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3459 motionEntry.downTime,
3460 usingProperties.value_or(motionEntry.pointerProperties),
3461 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003462 if (ATRACE_ENABLED()) {
3463 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3464 ") to MotionEvent(id=0x%" PRIx32 ").",
3465 motionEntry.id, resolvedMotion->id);
3466 ATRACE_NAME(message.c_str());
3467 }
3468
3469 // Set the resolved motion entry in the DispatchEntry.
3470 dispatchEntry->eventEntry = resolvedMotion;
3471 eventEntry = resolvedMotion;
3472 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003475 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3476 // devices being active at the same time in the same window, so if a new device is
3477 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003478 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003479 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003480 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003481 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003482 << connection->getInputChannelName() << " with event "
3483 << cancelEvent->getDescription();
3484 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
Prabir Pradhanc88b1fa2024-01-23 21:48:03 +00003485 createDispatchEntry(mIdGenerator, inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003486 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003487
3488 // Send these cancel events to the queue before sending the event from the new
3489 // device.
3490 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3491 }
3492
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003493 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003494 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003495 LOG(WARNING) << "channel " << connection->getInputChannelName()
3496 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003497 return; // skip the inconsistent event
3498 }
3499
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003500 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3501 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003502 // Skip reporting pointer down outside focus to the policy.
3503 break;
3504 }
3505
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003506 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003507 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508
3509 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003511 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003512 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003513 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3514 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003515 break;
3516 }
Chris Yef59a2f42020-10-16 12:55:26 -07003517 case EventEntry::Type::SENSOR: {
3518 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3519 break;
3520 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003521 case EventEntry::Type::CONFIGURATION_CHANGED:
3522 case EventEntry::Type::DEVICE_RESET: {
3523 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003524 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003525 break;
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
3529 // Remember that we are waiting for this dispatch to complete.
3530 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003531 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533
3534 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003535 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003536 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003537}
3538
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003539/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003540 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003541 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003542 * The first role is to log input interaction with windows, which helps determine what the user was
3543 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3544 * that user started interacting with launcher window, as well as any other window that received
3545 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3546 * when the set of tokens that received the event changes. It is not logged again as long as the
3547 * user is interacting with the same windows.
3548 *
3549 * The second role is to track input device activity for metrics collection. For each input event,
3550 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3551 * input_interaction logs, the device interaction is reported even when the set of interaction
3552 * tokens do not change.
3553 *
3554 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3555 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003556 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003557void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3558 const std::vector<InputTarget>& targets) {
3559 int32_t deviceId;
3560 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003561 // Skip ACTION_UP events, and all events other than keys and motions
3562 if (entry.type == EventEntry::Type::KEY) {
3563 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3564 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3565 return;
3566 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003567 deviceId = keyEntry.deviceId;
3568 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003569 } else if (entry.type == EventEntry::Type::MOTION) {
3570 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3571 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003572 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3573 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003574 return;
3575 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003576 deviceId = motionEntry.deviceId;
3577 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003578 } else {
3579 return; // Not a key or a motion
3580 }
3581
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003582 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003583 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003584 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003585 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003586 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003587 continue; // Skip windows that receive ACTION_OUTSIDE
3588 }
3589
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003590 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003591 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003592 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003593 if (target.windowHandle) {
3594 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3595 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003596 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003597
3598 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3599 REQUIRES(mLock) {
3600 scoped_unlock unlock(mLock);
3601 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3602 };
3603 postCommandLocked(std::move(command));
3604
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003605 if (newConnectionTokens == mInteractionConnectionTokens) {
3606 return; // no change
3607 }
3608 mInteractionConnectionTokens = newConnectionTokens;
3609
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003610 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003611 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08003612 targetList += connection->getInputChannelName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003613 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003614 std::string message = "Interaction with: " + targetList;
3615 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003616 message += "<none>";
3617 }
3618 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3619}
3620
chaviwfd6d3512019-03-25 13:23:49 -07003621void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003622 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003623 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003624 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3625 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003626 return;
3627 }
3628
Vishnu Nairc519ff72021-01-21 08:23:08 -08003629 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003630 if (focusedToken == token) {
3631 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003632 return;
3633 }
3634
Prabir Pradhancef936d2021-07-21 16:17:52 +00003635 auto command = [this, token]() REQUIRES(mLock) {
3636 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003637 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003638 };
3639 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640}
3641
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003642status_t InputDispatcher::publishMotionEvent(Connection& connection,
3643 DispatchEntry& dispatchEntry) const {
3644 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3645 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3646
3647 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003648 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003649
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003650 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003651 // Set the X and Y offset and X and Y scale depending on the input source.
3652 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003653 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003654 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3655 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003656 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003657 scaledCoords[i] = motionEntry.pointerCoords[i];
3658 // Don't apply window scale here since we don't want scale to affect raw
3659 // coordinates. The scale will be sent back to the client and applied
3660 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003661 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003662 }
3663 usingCoords = scaledCoords;
3664 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665 }
3666
3667 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3668
3669 // Publish the motion event.
3670 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003671 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3672 motionEntry.source, motionEntry.displayId, std::move(hmac),
3673 motionEntry.action, motionEntry.actionButton,
3674 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3675 motionEntry.metaState, motionEntry.buttonState,
3676 motionEntry.classification, dispatchEntry.transform,
3677 motionEntry.xPrecision, motionEntry.yPrecision,
3678 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3679 dispatchEntry.rawTransform, motionEntry.downTime,
3680 motionEntry.eventTime, motionEntry.getPointerCount(),
3681 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003682}
3683
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003685 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003686 ATRACE_NAME_IF(ATRACE_ENABLED(),
3687 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3688 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003689 if (DEBUG_DISPATCH_CYCLE) {
3690 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003693 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003694 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003696 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003697 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
3699 // Publish the event.
3700 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003701 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3702 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003703 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3705 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003706 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003707 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3708 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003711 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003712 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003713 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3714 keyEntry.deviceId, keyEntry.source,
3715 keyEntry.displayId, std::move(hmac),
3716 keyEntry.action, dispatchEntry->resolvedFlags,
3717 keyEntry.keyCode, keyEntry.scanCode,
3718 keyEntry.metaState, keyEntry.repeatCount,
3719 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003720 if (mTracer) {
3721 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3722 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 }
3725
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003726 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003727 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003728 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3729 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003730 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003731 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003732 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003733 if (mTracer) {
3734 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3735 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 break;
3737 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003738
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003739 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003740 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003741 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003742 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003743 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003744 break;
3745 }
3746
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003747 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3748 const TouchModeEntry& touchModeEntry =
3749 static_cast<const TouchModeEntry&>(eventEntry);
3750 status = connection->inputPublisher
3751 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3752 touchModeEntry.inTouchMode);
3753
3754 break;
3755 }
3756
Prabir Pradhan99987712020-11-10 18:43:05 -08003757 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3758 const auto& captureEntry =
3759 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3760 status = connection->inputPublisher
3761 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003762 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003763 break;
3764 }
3765
arthurhungb89ccb02020-12-30 16:19:01 +08003766 case EventEntry::Type::DRAG: {
3767 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3768 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3769 dragEntry.id, dragEntry.x,
3770 dragEntry.y,
3771 dragEntry.isExiting);
3772 break;
3773 }
3774
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003775 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003776 case EventEntry::Type::DEVICE_RESET:
3777 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003778 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003779 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
3784 // Check the result.
3785 if (status) {
3786 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003787 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003789 "This is unexpected because the wait queue is empty, so the pipe "
3790 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003791 "event to it, status=%s(%d)",
3792 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3793 status);
Harry Cutts33476232023-01-30 19:57:29 +00003794 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 } else {
3796 // Pipe is full and we are waiting for the app to finish process some events
3797 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003798 if (DEBUG_DISPATCH_CYCLE) {
3799 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3800 "waiting for the application to catch up",
3801 connection->getInputChannelName().c_str());
3802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 } else {
3805 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003806 "status=%s(%d)",
3807 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3808 status);
Harry Cutts33476232023-01-30 19:57:29 +00003809 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811 return;
3812 }
3813
3814 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003815 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3816 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3817 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003818 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003819 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003820 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003821 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003822 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824}
3825
chaviw09c8d2d2020-08-24 15:48:26 -07003826std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3827 size_t size;
3828 switch (event.type) {
3829 case VerifiedInputEvent::Type::KEY: {
3830 size = sizeof(VerifiedKeyEvent);
3831 break;
3832 }
3833 case VerifiedInputEvent::Type::MOTION: {
3834 size = sizeof(VerifiedMotionEvent);
3835 break;
3836 }
3837 }
3838 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3839 return mHmacKeyManager.sign(start, size);
3840}
3841
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003842const std::array<uint8_t, 32> InputDispatcher::getSignature(
3843 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003844 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003845 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003846 // Only sign events up and down events as the purely move events
3847 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003848 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003849 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003850
3851 VerifiedMotionEvent verifiedEvent =
3852 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3853 verifiedEvent.actionMasked = actionMasked;
3854 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3855 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003856}
3857
3858const std::array<uint8_t, 32> InputDispatcher::getSignature(
3859 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3860 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3861 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003862 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003863}
3864
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003866 const std::shared_ptr<Connection>& connection,
3867 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003868 if (DEBUG_DISPATCH_CYCLE) {
3869 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3870 connection->getInputChannelName().c_str(), seq, toString(handled));
3871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003873 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 return;
3875 }
3876
3877 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003878 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3879 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3880 };
3881 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882}
3883
3884void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003885 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003887 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003888 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3889 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
3892 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003893 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003894 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003895 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003896 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
3898 // The connection appears to be unrecoverably broken.
3899 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003900 if (connection->status == Connection::Status::NORMAL) {
3901 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
3903 if (notify) {
3904 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003905 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3906 connection->getInputChannelName().c_str());
3907
3908 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003909 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003910 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003911 };
3912 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 }
3914 }
3915}
3916
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003917void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003918 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003919 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003920 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 }
3922}
3923
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003924void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003926 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928}
3929
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003930int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3931 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003932 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003933 if (connection == nullptr) {
3934 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3935 connectionToken.get(), events);
3936 return 0; // remove the callback
3937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003939 bool notify;
3940 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3941 if (!(events & ALOOPER_EVENT_INPUT)) {
3942 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3943 "events=0x%x",
3944 connection->getInputChannelName().c_str(), events);
3945 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003948 nsecs_t currentTime = now();
3949 bool gotOne = false;
3950 status_t status = OK;
3951 for (;;) {
3952 Result<InputPublisher::ConsumerResponse> result =
3953 connection->inputPublisher.receiveConsumerResponse();
3954 if (!result.ok()) {
3955 status = result.error().code();
3956 break;
3957 }
3958
3959 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3960 const InputPublisher::Finished& finish =
3961 std::get<InputPublisher::Finished>(*result);
3962 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3963 finish.consumeTime);
3964 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003965 if (shouldReportMetricsForConnection(*connection)) {
3966 const InputPublisher::Timeline& timeline =
3967 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003968 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3969 connection->getToken(),
3970 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003971 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003972 }
3973 gotOne = true;
3974 }
3975 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003976 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003977 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 return 1;
3979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 }
3981
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003982 notify = status != DEAD_OBJECT || !connection->monitor;
3983 if (notify) {
3984 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3985 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3986 status);
3987 }
3988 } else {
3989 // Monitor channels are never explicitly unregistered.
3990 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003991 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003992 notify = !connection->monitor && stillHaveWindowHandle;
3993 if (notify) {
3994 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3995 connection->getInputChannelName().c_str(), events);
3996 }
3997 }
3998
3999 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004000 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004001 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002}
4003
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 const CancelationOptions& options) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004006 // Cancel windows (i.e. non-monitors).
4007 // A channel must have at least one window to receive any input. If a window was removed, the
4008 // event streams directed to the window will already have been canceled during window removal.
4009 // So there is no need to generate cancellations for connections without any windows.
4010 const auto [cancelPointers, cancelNonPointers] = expandCancellationMode(options.mode);
4011 // Generate cancellations for touched windows first. This is to avoid generating cancellations
4012 // through a non-touched window if there are more than one window for an input channel.
4013 if (cancelPointers) {
4014 for (const auto& [displayId, touchState] : mTouchStatesByDisplay) {
4015 if (options.displayId.has_value() && options.displayId != displayId) {
4016 continue;
4017 }
4018 for (const auto& touchedWindow : touchState.windows) {
4019 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
4020 }
4021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004023 // Follow up by generating cancellations for all windows, because we don't explicitly track
4024 // the windows that have an ongoing focus event stream.
4025 if (cancelNonPointers) {
4026 for (const auto& [_, handles] : mWindowHandlesByDisplay) {
4027 for (const auto& windowHandle : handles) {
4028 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
4029 }
4030 }
4031 }
4032
4033 // Cancel monitors.
4034 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035}
4036
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004038 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004039 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004040 for (const Monitor& monitor : monitors) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004041 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options,
4042 /*window=*/nullptr);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004043 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004044 }
4045}
4046
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004047void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4048 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options,
4049 const std::shared_ptr<Connection>& connection) {
4050 if (windowHandle == nullptr) {
4051 LOG(FATAL) << __func__ << ": Window handle must not be null";
4052 }
4053 if (connection) {
4054 // The connection can be optionally provided to avoid multiple lookups.
4055 if (windowHandle->getToken() != connection->getToken()) {
4056 LOG(FATAL) << __func__
4057 << ": Wrong connection provided for window: " << windowHandle->getName();
4058 }
4059 }
4060
4061 std::shared_ptr<Connection> resolvedConnection =
4062 connection ? connection : getConnectionLocked(windowHandle->getToken());
4063 if (!resolvedConnection) {
4064 LOG(DEBUG) << __func__ << "No connection found for window: " << windowHandle->getName();
4065 return;
4066 }
4067 synthesizeCancelationEventsForConnectionLocked(resolvedConnection, options, windowHandle);
4068}
4069
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004071 const std::shared_ptr<Connection>& connection, const CancelationOptions& options,
4072 const sp<WindowInfoHandle>& window) {
4073 if (!connection->monitor && window == nullptr) {
4074 LOG(FATAL) << __func__
4075 << ": Cannot send event to non-monitor channel without a window - channel: "
4076 << connection->getInputChannelName();
4077 }
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004078 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 return;
4080 }
4081
4082 nsecs_t currentTime = now();
4083
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004085 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004087 if (cancelationEvents.empty()) {
4088 return;
4089 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004090
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004091 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4092 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004093 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004094 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004095 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097
Arthur Hungb3307ee2021-10-14 10:57:37 +00004098 std::string reason = std::string("reason=").append(options.reason);
4099 android_log_event_list(LOGTAG_INPUT_CANCEL)
4100 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4101
hongzuo liu95785e22022-09-06 02:51:35 +00004102 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004103 // The target to use if we don't find a window associated with the channel.
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004104 const InputTarget fallbackTarget{connection};
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004105 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004106
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004107 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004109 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004110
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004111 switch (cancelationEventEntry->type) {
4112 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004113 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004114 if (window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004115 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4116 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004117 } else {
4118 targets.emplace_back(fallbackTarget);
4119 }
4120 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004123 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004124 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00004125 if (window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004126 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004127 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004128 pointerIndex++) {
4129 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4130 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004131 if (mDragState && mDragState->dragWindow->getToken() == token &&
4132 pointerIds.test(mDragState->pointerId)) {
4133 LOG(INFO) << __func__
4134 << ": Canceling drag and drop because the pointers for the drag "
4135 "window are being canceled.";
4136 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4137 mDragState.reset();
4138 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004139 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4140 ftl::Flags<InputTarget::Flags>(), pointerIds,
4141 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004142 } else {
4143 targets.emplace_back(fallbackTarget);
4144 const auto it = mDisplayInfos.find(motionEntry.displayId);
4145 if (it != mDisplayInfos.end()) {
4146 targets.back().displayTransform = it->second.transform;
4147 targets.back().setDefaultPointerTransform(it->second.transform);
4148 }
4149 }
4150 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004151 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004153 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004154 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004155 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4156 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004157 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004158 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004159 break;
4160 }
4161 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004162 case EventEntry::Type::DEVICE_RESET:
4163 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004164 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004165 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004166 break;
4167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004170 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004171 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004173
hongzuo liu95785e22022-09-06 02:51:35 +00004174 // If the outbound queue was previously empty, start the dispatch cycle going.
4175 if (wasEmpty && !connection->outboundQueue.empty()) {
4176 startDispatchCycleLocked(currentTime, connection);
4177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178}
4179
Svet Ganov5d3bc372020-01-26 23:11:07 -08004180void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004181 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004182 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004183 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004184 return;
4185 }
4186
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004188 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004189
4190 if (downEvents.empty()) {
4191 return;
4192 }
4193
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004194 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4196 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004197 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004198
Prabir Pradhanfeca0572024-02-06 00:43:11 +00004199 const auto [_, touchedWindowState, displayId] =
4200 findTouchStateWindowAndDisplayLocked(connection->getToken());
4201 if (touchedWindowState == nullptr) {
4202 LOG(FATAL) << __func__ << ": Touch state is out of sync: No touched window for token";
4203 }
4204 const auto& windowHandle = touchedWindowState->windowHandle;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205
hongzuo liu95785e22022-09-06 02:51:35 +00004206 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004207 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004208 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004209 switch (downEventEntry->type) {
4210 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004211 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4212 if (windowHandle != nullptr) {
4213 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004214 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004215 pointerIndex++) {
4216 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4217 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004218 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4219 targetFlags, pointerIds, motionEntry.downTime,
4220 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004221 } else {
Prabir Pradhanc32a4112024-01-23 23:20:37 +00004222 targets.emplace_back(connection, targetFlags);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004223 const auto it = mDisplayInfos.find(motionEntry.displayId);
4224 if (it != mDisplayInfos.end()) {
4225 targets.back().displayTransform = it->second.transform;
4226 targets.back().setDefaultPointerTransform(it->second.transform);
4227 }
4228 }
4229 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004230 break;
4231 }
4232
4233 case EventEntry::Type::KEY:
4234 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004235 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004236 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004237 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004238 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004239 case EventEntry::Type::SENSOR:
4240 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004241 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004242 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004243 break;
4244 }
4245 }
4246
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004247 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004248 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004249 }
4250
hongzuo liu95785e22022-09-06 02:51:35 +00004251 // If the outbound queue was previously empty, start the dispatch cycle going.
4252 if (wasEmpty && !connection->outboundQueue.empty()) {
4253 startDispatchCycleLocked(downTime, connection);
4254 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004255}
4256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004257std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004258 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4259 nsecs_t splitDownTime) {
4260 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
4262 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004263 std::vector<PointerProperties> splitPointerProperties;
4264 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004266 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 uint32_t splitPointerCount = 0;
4268
4269 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004272 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004274 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004276 splitPointerProperties.push_back(pointerProperties);
4277 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 splitPointerCount += 1;
4279 }
4280 }
4281
4282 if (splitPointerCount != pointerIds.count()) {
4283 // This is bad. We are missing some of the pointers that we expected to deliver.
4284 // Most likely this indicates that we received an ACTION_MOVE events that has
4285 // different pointer ids than we expected based on the previous ACTION_DOWN
4286 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4287 // in this way.
4288 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004289 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004290 "a broken sequence of pointer ids from the input device: %s",
4291 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004292 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 }
4294
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004295 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4298 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004299 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004301 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004303 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 if (pointerIds.count() == 1) {
4305 // The first/last pointer went down/up.
4306 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004308 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4309 ? AMOTION_EVENT_ACTION_CANCEL
4310 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 } else {
4312 // A secondary pointer went down/up.
4313 uint32_t splitPointerIndex = 0;
4314 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4315 splitPointerIndex += 1;
4316 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 action = maskedAction |
4318 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 }
4320 } else {
4321 // An unrelated pointer changed.
4322 action = AMOTION_EVENT_ACTION_MOVE;
4323 }
4324 }
4325
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004326 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4327 logDispatchStateLocked();
4328 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4329 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4330 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004331 }
4332
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004333 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004334 ATRACE_NAME_IF(ATRACE_ENABLED(),
4335 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4336 ").",
4337 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004338 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004339 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4340 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341 originalMotionEntry.deviceId, originalMotionEntry.source,
4342 originalMotionEntry.displayId,
4343 originalMotionEntry.policyFlags, action,
4344 originalMotionEntry.actionButton,
4345 originalMotionEntry.flags, originalMotionEntry.metaState,
4346 originalMotionEntry.buttonState,
4347 originalMotionEntry.classification,
4348 originalMotionEntry.edgeFlags,
4349 originalMotionEntry.xPrecision,
4350 originalMotionEntry.yPrecision,
4351 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004352 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004353 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 return splitMotionEntry;
4356}
4357
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004358void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4359 std::scoped_lock _l(mLock);
4360 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4361}
4362
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004363void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004364 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004365 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
Antonio Kantekf16f2832021-09-28 04:39:20 +00004368 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004370 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004372 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004374 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 } // release lock
4376
4377 if (needWake) {
4378 mLooper->wake();
4379 }
4380}
4381
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004382void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004383 ALOGD_IF(debugInboundEventDetails(),
4384 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4385 ", deviceId=%d, source=%s, displayId=%" PRId32
4386 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4387 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004388 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4389 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4390 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004391 Result<void> keyCheck = validateKeyEvent(args.action);
4392 if (!keyCheck.ok()) {
4393 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 return;
4395 }
4396
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004397 uint32_t policyFlags = args.policyFlags;
4398 int32_t flags = args.flags;
4399 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004400 // InputDispatcher tracks and generates key repeats on behalf of
4401 // whatever notifies it, so repeatCount should always be set to 0
4402 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4404 policyFlags |= POLICY_FLAG_VIRTUAL;
4405 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 if (policyFlags & POLICY_FLAG_FUNCTION) {
4408 metaState |= AMETA_FUNCTION_ON;
4409 }
4410
4411 policyFlags |= POLICY_FLAG_TRUSTED;
4412
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004413 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004415 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4416 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4417 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Michael Wright2b3c3302018-03-02 17:19:13 +00004419 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004420 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004421 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4422 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425
Antonio Kantekf16f2832021-09-28 04:39:20 +00004426 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 { // acquire lock
4428 mLock.lock();
4429
4430 if (shouldSendKeyToInputFilterLocked(args)) {
4431 mLock.unlock();
4432
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004433 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004434 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 return; // event was consumed by the filter
4436 }
4437
4438 mLock.lock();
4439 }
4440
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004441 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004442 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4443 args.deviceId, args.source, args.displayId, policyFlags,
4444 args.action, flags, keyCode, args.scanCode, metaState,
4445 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004446 if (mTracer) {
4447 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004450 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 mLock.unlock();
4452 } // release lock
4453
4454 if (needWake) {
4455 mLooper->wake();
4456 }
4457}
4458
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004459bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 return mInputFilterEnabled;
4461}
4462
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004463void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004464 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004465 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004466 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004467 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004468 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4469 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4471 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4472 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4473 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4474 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004475 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004476 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4477 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004478 i, args.pointerProperties[i].id,
4479 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4480 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4481 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4482 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4483 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4484 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4485 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4486 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4487 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4488 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004491
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004492 Result<void> motionCheck =
4493 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4494 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004495 if (!motionCheck.ok()) {
4496 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4497 return;
4498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004500 if (DEBUG_VERIFY_EVENTS) {
4501 auto [it, _] =
4502 mVerifiersByDisplay.try_emplace(args.displayId,
4503 StringPrintf("display %" PRId32, args.displayId));
4504 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004505 it->second.processMovement(args.deviceId, args.source, args.action,
4506 args.getPointerCount(), args.pointerProperties.data(),
4507 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004508 if (!result.ok()) {
4509 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4510 }
4511 }
4512
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004513 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004515
4516 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004517 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4518 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004519 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4520 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004521 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
Antonio Kantekf16f2832021-09-28 04:39:20 +00004524 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 { // acquire lock
4526 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004527 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4528 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4529 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004530 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004531 if (touchStateIt != mTouchStatesByDisplay.end()) {
4532 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004533 if (touchState.hasTouchingPointers(args.deviceId) ||
4534 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004535 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4536 }
4537 }
4538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539
4540 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004541 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004542 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004543 displayTransform = it->second.transform;
4544 }
4545
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 mLock.unlock();
4547
4548 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004549 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4550 args.action, args.actionButton, args.flags, args.edgeFlags,
4551 args.metaState, args.buttonState, args.classification,
4552 displayTransform, args.xPrecision, args.yPrecision,
4553 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004554 args.downTime, args.eventTime, args.getPointerCount(),
4555 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556
4557 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004558 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 return; // event was consumed by the filter
4560 }
4561
4562 mLock.lock();
4563 }
4564
4565 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004566 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004567 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4568 args.deviceId, args.source, args.displayId,
4569 policyFlags, args.action, args.actionButton,
4570 args.flags, args.metaState, args.buttonState,
4571 args.classification, args.edgeFlags, args.xPrecision,
4572 args.yPrecision, args.xCursorPosition,
4573 args.yCursorPosition, args.downTime,
4574 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004575 if (mTracer) {
4576 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004579 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4580 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004581 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004582 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004583 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4584 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4585 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004586 }
4587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004588 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 mLock.unlock();
4590 } // release lock
4591
4592 if (needWake) {
4593 mLooper->wake();
4594 }
4595}
4596
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004597void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004598 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004599 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4600 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004601 args.id, args.eventTime, args.deviceId, args.source,
4602 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004603 }
Chris Yef59a2f42020-10-16 12:55:26 -07004604
Antonio Kantekf16f2832021-09-28 04:39:20 +00004605 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004606 { // acquire lock
4607 mLock.lock();
4608
4609 // Just enqueue a new sensor event.
4610 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4612 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4613 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004614
4615 needWake = enqueueInboundEventLocked(std::move(newEntry));
4616 mLock.unlock();
4617 } // release lock
4618
4619 if (needWake) {
4620 mLooper->wake();
4621 }
4622}
4623
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004624void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004625 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004626 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4627 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004628 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004629 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004630}
4631
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004632bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004633 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634}
4635
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004636void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004637 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004638 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4639 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004640 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004643 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004645 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646}
4647
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004648void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004649 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4651 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653
Antonio Kantekf16f2832021-09-28 04:39:20 +00004654 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004656 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004659 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004660 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004661
4662 for (auto& [_, verifier] : mVerifiersByDisplay) {
4663 verifier.resetDevice(args.deviceId);
4664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 } // release lock
4666
4667 if (needWake) {
4668 mLooper->wake();
4669 }
4670}
4671
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004672void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004673 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004674 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4675 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004676 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004677
Antonio Kantekf16f2832021-09-28 04:39:20 +00004678 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004679 { // acquire lock
4680 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004681 auto entry =
4682 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004683 needWake = enqueueInboundEventLocked(std::move(entry));
4684 } // release lock
4685
4686 if (needWake) {
4687 mLooper->wake();
4688 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004689}
4690
Prabir Pradhan5735a322022-04-11 17:23:34 +00004691InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004692 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004693 InputEventInjectionSync syncMode,
4694 std::chrono::milliseconds timeout,
4695 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004696 Result<void> eventValidation = validateInputEvent(*event);
4697 if (!eventValidation.ok()) {
4698 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4699 return InputEventInjectionResult::FAILED;
4700 }
4701
Prabir Pradhan65613802023-02-22 23:36:58 +00004702 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004703 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4704 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4705 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4706 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004707 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004708 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
Prabir Pradhan5735a322022-04-11 17:23:34 +00004710 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004712 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004713 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4714 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4715 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4716 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4717 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004718 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004719 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004720 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004721 }
4722
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004723 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4724 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4725
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004726 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004728 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004729 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004730 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004731 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004732 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4733 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4734 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004735 int32_t keyCode = incomingKey.getKeyCode();
4736 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004737 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004738 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004739 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4740 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4741 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4744 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004745 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746
4747 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4748 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004749 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004750 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4751 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4752 std::to_string(t.duration().count()).c_str());
4753 }
4754 }
4755
4756 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004757 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004758 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4759 incomingKey.getEventTime(), resolvedDeviceId,
4760 incomingKey.getSource(), incomingKey.getDisplayId(),
4761 policyFlags, action, flags, keyCode,
4762 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004763 incomingKey.getRepeatCount(),
4764 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004765 if (mTracer) {
4766 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4767 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004768 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 }
4771
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004772 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004773 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004774 const bool isPointerEvent =
4775 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4776 // If a pointer event has no displayId specified, inject it to the default display.
4777 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4778 ? ADISPLAY_ID_DEFAULT
4779 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004780 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781
4782 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004783 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004785 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4786 motionEvent.getAction(), eventTime,
4787 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004788 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4789 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4790 std::to_string(t.duration().count()).c_str());
4791 }
4792 }
4793
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004794 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4795 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4796 }
4797
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004799 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004800 const size_t pointerCount = motionEvent.getPointerCount();
4801 const std::vector<PointerProperties>
4802 pointerProperties(motionEvent.getPointerProperties(),
4803 motionEvent.getPointerProperties() + pointerCount);
4804
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004805 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004806 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004807 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4808 *sampleEventTimes, resolvedDeviceId,
4809 motionEvent.getSource(), displayId, policyFlags,
4810 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004811 motionEvent.getActionButton(), flags,
4812 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004813 motionEvent.getButtonState(),
4814 motionEvent.getClassification(),
4815 motionEvent.getEdgeFlags(),
4816 motionEvent.getXPrecision(),
4817 motionEvent.getYPrecision(),
4818 motionEvent.getRawXCursorPosition(),
4819 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004820 motionEvent.getDownTime(), pointerProperties,
4821 std::vector<PointerCoords>(samplePointerCoords,
4822 samplePointerCoords +
4823 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004824 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004825 if (mTracer) {
4826 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4827 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004828 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004829 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004831 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004832 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004833 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4834 resolvedDeviceId, motionEvent.getSource(), displayId,
4835 policyFlags, motionEvent.getAction(),
4836 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004837 motionEvent.getMetaState(), motionEvent.getButtonState(),
4838 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4839 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4840 motionEvent.getRawXCursorPosition(),
4841 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4842 pointerProperties,
4843 std::vector<PointerCoords>(samplePointerCoords,
4844 samplePointerCoords +
4845 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004846 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4847 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004848 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 }
4850 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004853 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004854 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004855 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 }
4857
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004859 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004860 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004861 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004863 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004864 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
4867 mLock.unlock();
4868
4869 if (needWake) {
4870 mLooper->wake();
4871 }
4872
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004873 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004875 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004877 if (syncMode == InputEventInjectionSync::NONE) {
4878 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 } else {
4880 for (;;) {
4881 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004882 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 break;
4884 }
4885
4886 nsecs_t remainingTimeout = endTime - now();
4887 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004888 if (DEBUG_INJECTION) {
4889 ALOGD("injectInputEvent - Timed out waiting for injection result "
4890 "to become available.");
4891 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004892 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 break;
4894 }
4895
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004896 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 }
4898
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004899 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4900 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004902 if (DEBUG_INJECTION) {
4903 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4904 injectionState->pendingForegroundDispatches);
4905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 nsecs_t remainingTimeout = endTime - now();
4907 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004908 if (DEBUG_INJECTION) {
4909 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4910 "dispatches to finish.");
4911 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004912 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 break;
4914 }
4915
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004916 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 }
4918 }
4919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 } // release lock
4921
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004922 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004923 LOG(INFO) << "injectInputEvent - Finished with result "
4924 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
4927 return injectionResult;
4928}
4929
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004930std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004931 std::array<uint8_t, 32> calculatedHmac;
4932 std::unique_ptr<VerifiedInputEvent> result;
4933 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004934 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004935 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4936 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4937 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004938 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004939 break;
4940 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004941 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004942 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4943 VerifiedMotionEvent verifiedMotionEvent =
4944 verifiedMotionEventFromMotionEvent(motionEvent);
4945 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004946 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004947 break;
4948 }
4949 default: {
Siarhei Vishniakouef2b4502023-12-28 11:51:47 -08004950 LOG(ERROR) << "Cannot verify events of type " << ftl::enum_string(event.getType());
Gang Wange9087892020-01-07 12:17:14 -05004951 return nullptr;
4952 }
4953 }
4954 if (calculatedHmac == INVALID_HMAC) {
4955 return nullptr;
4956 }
tyiu1573a672023-02-21 22:38:32 +00004957 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004958 return nullptr;
4959 }
4960 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004961}
4962
Prabir Pradhan24047542023-11-02 17:14:59 +00004963void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004964 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004965 if (!entry.injectionState) {
4966 // Not an injected event.
4967 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004969
4970 InjectionState& injectionState = *entry.injectionState;
4971 if (DEBUG_INJECTION) {
4972 LOG(INFO) << "Setting input event injection result to "
4973 << ftl::enum_string(injectionResult);
4974 }
4975
4976 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4977 // Log the outcome since the injector did not wait for the injection result.
4978 switch (injectionResult) {
4979 case InputEventInjectionResult::SUCCEEDED:
4980 ALOGV("Asynchronous input event injection succeeded.");
4981 break;
4982 case InputEventInjectionResult::TARGET_MISMATCH:
4983 ALOGV("Asynchronous input event injection target mismatch.");
4984 break;
4985 case InputEventInjectionResult::FAILED:
4986 ALOGW("Asynchronous input event injection failed.");
4987 break;
4988 case InputEventInjectionResult::TIMED_OUT:
4989 ALOGW("Asynchronous input event injection timed out.");
4990 break;
4991 case InputEventInjectionResult::PENDING:
4992 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4993 break;
4994 }
4995 }
4996
4997 injectionState.injectionResult = injectionResult;
4998 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999}
5000
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005001void InputDispatcher::transformMotionEntryForInjectionLocked(
5002 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005003 // Input injection works in the logical display coordinate space, but the input pipeline works
5004 // display space, so we need to transform the injected events accordingly.
5005 const auto it = mDisplayInfos.find(entry.displayId);
5006 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00005007 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005008
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00005009 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
5010 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
5011 const vec2 cursor =
5012 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
5013 {entry.xCursorPosition, entry.yCursorPosition});
5014 entry.xCursorPosition = cursor.x;
5015 entry.yCursorPosition = cursor.y;
5016 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07005017 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08005018 entry.pointerCoords[i] =
5019 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
5020 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07005021 }
5022}
5023
Prabir Pradhan24047542023-11-02 17:14:59 +00005024void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005025 if (entry.injectionState) {
5026 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
5028}
5029
Prabir Pradhan24047542023-11-02 17:14:59 +00005030void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005031 if (entry.injectionState) {
5032 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005034 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005035 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037 }
5038}
5039
chaviw98318de2021-05-19 16:45:23 -05005040const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005041 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005042 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005043 auto it = mWindowHandlesByDisplay.find(displayId);
5044 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005045}
5046
chaviw98318de2021-05-19 16:45:23 -05005047sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005048 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005049 if (windowHandleToken == nullptr) {
5050 return nullptr;
5051 }
5052
Prabir Pradhan16463382023-10-12 23:03:19 +00005053 if (!displayId) {
5054 // Look through all displays.
5055 for (auto& it : mWindowHandlesByDisplay) {
5056 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5057 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5058 if (windowHandle->getToken() == windowHandleToken) {
5059 return windowHandle;
5060 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005063 return nullptr;
5064 }
5065
Prabir Pradhan16463382023-10-12 23:03:19 +00005066 // Only look through the requested display.
5067 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005068 if (windowHandle->getToken() == windowHandleToken) {
5069 return windowHandle;
5070 }
5071 }
5072 return nullptr;
5073}
5074
chaviw98318de2021-05-19 16:45:23 -05005075sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5076 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005077 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005078 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5079 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005080 if (handle->getId() == windowHandle->getId() &&
5081 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005082 if (windowHandle->getInfo()->displayId != it.first) {
5083 ALOGE("Found window %s in display %" PRId32
5084 ", but it should belong to display %" PRId32,
5085 windowHandle->getName().c_str(), it.first,
5086 windowHandle->getInfo()->displayId);
5087 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005088 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 }
5091 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005092 return nullptr;
5093}
5094
chaviw98318de2021-05-19 16:45:23 -05005095sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005096 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5097 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098}
5099
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005100ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5101 auto displayInfoIt = mDisplayInfos.find(displayId);
5102 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5103 : kIdentityTransform;
5104}
5105
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005106bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5107 const MotionEntry& motionEntry) const {
5108 const WindowInfo& info = *window->getInfo();
5109
5110 // Skip spy window targets that are not valid for targeted injection.
5111 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005112 return false;
5113 }
5114
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005115 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5116 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5117 return false;
5118 }
5119
5120 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5121 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5122 window->getName().c_str());
5123 return false;
5124 }
5125
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005126 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005127 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005128 ALOGW("Not sending touch to %s because there's no corresponding connection",
5129 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 return false;
5131 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005132
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005133 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005134 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005135 return false;
5136 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005137
5138 // Drop events that can't be trusted due to occlusion
5139 const auto [x, y] = resolveTouchedPosition(motionEntry);
5140 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5141 if (!isTouchTrustedLocked(occlusionInfo)) {
5142 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005143 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005144 for (const auto& log : occlusionInfo.debugInfo) {
5145 ALOGD("%s", log.c_str());
5146 }
5147 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005148 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5149 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005150 return false;
5151 }
5152
5153 // Drop touch events if requested by input feature
5154 if (shouldDropInput(motionEntry, window)) {
5155 return false;
5156 }
5157
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005158 // Ignore touches if stylus is down anywhere on screen
5159 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5160 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5161 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5162 return false;
5163 }
5164
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005165 return true;
5166}
5167
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005168void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005169 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5170 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 // Remove all handles on a display if there are no windows left.
5172 mWindowHandlesByDisplay.erase(displayId);
5173 return;
5174 }
5175
5176 // Since we compare the pointer of input window handles across window updates, we need
5177 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005178 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5179 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5180 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005181 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005182 }
5183
chaviw98318de2021-05-19 16:45:23 -05005184 std::vector<sp<WindowInfoHandle>> newHandles;
5185 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005186 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005187 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005188 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005189 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005190 const bool canReceiveInput =
5191 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5192 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005193 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005194 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005195 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005196 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005197 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005198 }
5199
5200 if (info->displayId != displayId) {
5201 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5202 handle->getName().c_str(), displayId, info->displayId);
5203 continue;
5204 }
5205
Robert Carredd13602020-04-13 17:24:34 -07005206 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5207 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005208 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005209 oldHandle->updateFrom(handle);
5210 newHandles.push_back(oldHandle);
5211 } else {
5212 newHandles.push_back(handle);
5213 }
5214 }
5215
5216 // Insert or replace
5217 mWindowHandlesByDisplay[displayId] = newHandles;
5218}
5219
Arthur Hungb92218b2018-08-14 12:00:21 +08005220/**
5221 * Called from InputManagerService, update window handle list by displayId that can receive input.
5222 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5223 * If set an empty list, remove all handles from the specific display.
5224 * For focused handle, check if need to change and send a cancel event to previous one.
5225 * For removed handle, check if need to send a cancel event if already in touch.
5226 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005227void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005228 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005229 if (DEBUG_FOCUS) {
5230 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005231 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005232 windowList += iwh->getName() + " ";
5233 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005234 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236
Prabir Pradhand65552b2021-10-07 11:23:50 -07005237 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005238 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005239 const WindowInfo& info = *window->getInfo();
5240
5241 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005242 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005243 if (noInputWindow && window->getToken() != nullptr) {
5244 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5245 window->getName().c_str());
5246 window->releaseChannel();
5247 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005248
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005249 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005250 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5251 !info.inputConfig.test(
5252 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005253 "%s has feature SPY, but is not a trusted overlay.",
5254 window->getName().c_str());
5255
Prabir Pradhand65552b2021-10-07 11:23:50 -07005256 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005257 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5258 !info.inputConfig.test(
5259 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005260 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5261 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005262 }
5263
Arthur Hung72d8dc32020-03-28 00:48:39 +00005264 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005265 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005266 const sp<WindowInfoHandle> removedFocusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267
chaviw98318de2021-05-19 16:45:23 -05005268 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005269
chaviw98318de2021-05-19 16:45:23 -05005270 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005271
Vishnu Nairc519ff72021-01-21 08:23:08 -08005272 std::optional<FocusResolver::FocusChanges> changes =
5273 mFocusResolver.setInputWindows(displayId, windowHandles);
5274 if (changes) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005275 onFocusChangedLocked(*changes, removedFocusedWindowHandle);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005278 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5279 mTouchStatesByDisplay.find(displayId);
5280 if (stateIt != mTouchStatesByDisplay.end()) {
5281 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005282 for (size_t i = 0; i < state.windows.size();) {
5283 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005284 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005285 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5286 << " in display %" << displayId;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005287 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5288 "touched window was removed");
5289 synthesizeCancelationEventsForWindowLocked(touchedWindow.windowHandle, options);
5290 // Since we are about to drop the touch, cancel the events for the wallpaper as
5291 // well.
5292 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
5293 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5294 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
5295 if (const auto& ww = state.getWallpaperWindow(); ww) {
5296 synthesizeCancelationEventsForWindowLocked(ww, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005299 state.windows.erase(state.windows.begin() + i);
5300 } else {
5301 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 }
5303 }
arthurhungb89ccb02020-12-30 16:19:01 +08005304
arthurhung6d4bed92021-03-17 11:59:33 +08005305 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005306 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005307 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005308 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005309 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005310 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5311 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005312 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005313 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005314 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005315
Arthur Hung72d8dc32020-03-28 00:48:39 +00005316 // Release information for windows that are no longer present.
5317 // This ensures that unused input channels are released promptly.
5318 // Otherwise, they might stick around until the window handle is destroyed
5319 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005320 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005321 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005322 if (DEBUG_FOCUS) {
5323 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005324 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005325 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005326 }
chaviw291d88a2019-02-14 10:33:58 -08005327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328}
5329
5330void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005331 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005332 if (DEBUG_FOCUS) {
5333 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5334 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5335 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005336 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005337 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005338 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 } // release lock
5340
5341 // Wake up poll loop since it may need to make new input dispatching choices.
5342 mLooper->wake();
5343}
5344
Vishnu Nair599f1412021-06-21 10:39:58 -07005345void InputDispatcher::setFocusedApplicationLocked(
5346 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5347 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5348 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5349
5350 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5351 return; // This application is already focused. No need to wake up or change anything.
5352 }
5353
5354 // Set the new application handle.
5355 if (inputApplicationHandle != nullptr) {
5356 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5357 } else {
5358 mFocusedApplicationHandlesByDisplay.erase(displayId);
5359 }
5360
5361 // No matter what the old focused application was, stop waiting on it because it is
5362 // no longer focused.
5363 resetNoFocusedWindowTimeoutLocked();
5364}
5365
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005366void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5367 if (interval.count() < 0) {
5368 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5369 }
5370 std::scoped_lock _l(mLock);
5371 mMinTimeBetweenUserActivityPokes = interval;
5372}
5373
Tiger Huang721e26f2018-07-24 22:26:19 +08005374/**
5375 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5376 * the display not specified.
5377 *
5378 * We track any unreleased events for each window. If a window loses the ability to receive the
5379 * released event, we will send a cancel event to it. So when the focused display is changed, we
5380 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5381 * display. The display-specified events won't be affected.
5382 */
5383void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005384 if (DEBUG_FOCUS) {
5385 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5386 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005388 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005389
5390 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005391 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005392 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005393 if (oldFocusedWindowToken != nullptr) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005394 const auto windowHandle =
5395 getWindowHandleLocked(oldFocusedWindowToken, mFocusedDisplayId);
5396 if (windowHandle == nullptr) {
5397 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Tiger Huang721e26f2018-07-24 22:26:19 +08005398 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00005399 CancelationOptions
5400 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
5401 "The display which contains this window no longer has focus.");
5402 options.displayId = ADISPLAY_ID_NONE;
5403 synthesizeCancelationEventsForWindowLocked(windowHandle, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005404 }
5405 mFocusedDisplayId = displayId;
5406
Chris Ye3c2d6f52020-08-09 10:39:48 -07005407 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005408 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005409 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005410
Vishnu Nairad321cd2020-08-20 16:40:21 -07005411 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005412 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005413 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005414 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005415 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005416 }
5417 }
5418 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005419 } // release lock
5420
5421 // Wake up poll loop since it may need to make new input dispatching choices.
5422 mLooper->wake();
5423}
5424
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005426 if (DEBUG_FOCUS) {
5427 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429
5430 bool changed;
5431 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005432 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433
5434 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5435 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005436 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 }
5438
5439 if (mDispatchEnabled && !enabled) {
5440 resetAndDropEverythingLocked("dispatcher is being disabled");
5441 }
5442
5443 mDispatchEnabled = enabled;
5444 mDispatchFrozen = frozen;
5445 changed = true;
5446 } else {
5447 changed = false;
5448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 } // release lock
5450
5451 if (changed) {
5452 // Wake up poll loop since it may need to make new input dispatching choices.
5453 mLooper->wake();
5454 }
5455}
5456
5457void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005458 if (DEBUG_FOCUS) {
5459 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
5462 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005463 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464
5465 if (mInputFilterEnabled == enabled) {
5466 return;
5467 }
5468
5469 mInputFilterEnabled = enabled;
5470 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5471 } // release lock
5472
5473 // Wake up poll loop since there might be work to do to drop everything.
5474 mLooper->wake();
5475}
5476
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005477bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005478 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005479 bool needWake = false;
5480 {
5481 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005482 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005483 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005484 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005485 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5486 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005487 mTouchModePerDisplay.count(displayId) == 0
5488 ? "not set"
5489 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5490
Antonio Kantek15beb512022-06-13 22:35:41 +00005491 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5492 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005493 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005494 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005495 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005496 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5497 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005498 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005499 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005500 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005501 return false;
5502 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005503 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005504 mTouchModePerDisplay[displayId] = inTouchMode;
5505 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5506 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005507 needWake = enqueueInboundEventLocked(std::move(entry));
5508 } // release lock
5509
5510 if (needWake) {
5511 mLooper->wake();
5512 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005513 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005514}
5515
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005516bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005517 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5518 if (focusedToken == nullptr) {
5519 return false;
5520 }
5521 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5522 return isWindowOwnedBy(windowHandle, pid, uid);
5523}
5524
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005525bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005526 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5527 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5528 const sp<WindowInfoHandle> windowHandle =
5529 getWindowHandleLocked(connectionToken);
5530 return isWindowOwnedBy(windowHandle, pid, uid);
5531 }) != mInteractionConnectionTokens.end();
5532}
5533
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005534void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5535 if (opacity < 0 || opacity > 1) {
5536 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5537 return;
5538 }
5539
5540 std::scoped_lock lock(mLock);
5541 mMaximumObscuringOpacityForTouch = opacity;
5542}
5543
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005544std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5545InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005546 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5547 for (TouchedWindow& w : state.windows) {
5548 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005549 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005550 }
5551 }
5552 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005553 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005554}
5555
arthurhungb89ccb02020-12-30 16:19:01 +08005556bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5557 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005558 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005559 if (DEBUG_FOCUS) {
5560 ALOGD("Trivial transfer to same window.");
5561 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005562 return true;
5563 }
5564
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005566 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567
Arthur Hungabbb9d82021-09-01 14:52:30 +00005568 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005569 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005570
Arthur Hungabbb9d82021-09-01 14:52:30 +00005571 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005572 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 return false;
5574 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005575 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5576 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005577 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5578 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005579 return false;
5580 }
5581 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005582
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005583 const sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
5584 const sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5585 if (!toWindowHandle) {
5586 ALOGW("Cannot transfer touch because the transfer target window was not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005587 return false;
5588 }
5589
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005590 if (DEBUG_FOCUS) {
5591 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005592 touchedWindow->windowHandle->getName().c_str(),
5593 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 }
5595
Arthur Hungabbb9d82021-09-01 14:52:30 +00005596 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005597 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005598 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005599 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600
Arthur Hungabbb9d82021-09-01 14:52:30 +00005601 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005602 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005603 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005604 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005605 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005606 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005607 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005608 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005609 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610
Arthur Hungabbb9d82021-09-01 14:52:30 +00005611 // Store the dragging window.
5612 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005613 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005614 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5615 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005616 return false;
5617 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005618 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005619 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005620 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 }
5622
Arthur Hungabbb9d82021-09-01 14:52:30 +00005623 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005624 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5625 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005626 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005627 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005628 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5629 "transferring touch from this window to another window");
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00005630 synthesizeCancelationEventsForWindowLocked(fromWindowHandle, options, fromConnection);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005631 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5632 newTargetFlags);
5633
5634 // Check if the wallpaper window should deliver the corresponding event.
5635 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005636 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 } // release lock
5639
5640 // Wake up poll loop since it may need to make new input dispatching choices.
5641 mLooper->wake();
5642 return true;
5643}
5644
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005645/**
5646 * Get the touched foreground window on the given display.
5647 * Return null if there are no windows touched on that display, or if more than one foreground
5648 * window is being touched.
5649 */
5650sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5651 auto stateIt = mTouchStatesByDisplay.find(displayId);
5652 if (stateIt == mTouchStatesByDisplay.end()) {
5653 ALOGI("No touch state on display %" PRId32, displayId);
5654 return nullptr;
5655 }
5656
5657 const TouchState& state = stateIt->second;
5658 sp<WindowInfoHandle> touchedForegroundWindow;
5659 // If multiple foreground windows are touched, return nullptr
5660 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005661 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005662 if (touchedForegroundWindow != nullptr) {
5663 ALOGI("Two or more foreground windows: %s and %s",
5664 touchedForegroundWindow->getName().c_str(),
5665 window.windowHandle->getName().c_str());
5666 return nullptr;
5667 }
5668 touchedForegroundWindow = window.windowHandle;
5669 }
5670 }
5671 return touchedForegroundWindow;
5672}
5673
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005674// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005675bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005676 sp<IBinder> fromToken;
5677 { // acquire lock
5678 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005679 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005680 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005681 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5682 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005683 return false;
5684 }
5685
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005686 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5687 if (from == nullptr) {
5688 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5689 return false;
5690 }
5691
5692 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005693 } // release lock
5694
5695 return transferTouchFocus(fromToken, destChannelToken);
5696}
5697
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005699 if (DEBUG_FOCUS) {
5700 ALOGD("Resetting and dropping all events (%s).", reason);
5701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702
Michael Wrightfb04fd52022-11-24 22:31:11 +00005703 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 synthesizeCancelationEventsForAllConnectionsLocked(options);
5705
5706 resetKeyRepeatLocked();
5707 releasePendingEventLocked();
5708 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005709 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005711 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005712 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713}
5714
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005715void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005716 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 dumpDispatchStateLocked(dump);
5718
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005719 std::istringstream stream(dump);
5720 std::string line;
5721
5722 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005723 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724 }
5725}
5726
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005727std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005728 std::string dump;
5729
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005730 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5731 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005732
5733 std::string windowName = "None";
5734 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005735 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005736 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5737 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5738 : "token has capture without window";
5739 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005740 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005741
5742 return dump;
5743}
5744
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005745void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005746 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5747 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5748 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005749 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Tiger Huang721e26f2018-07-24 22:26:19 +08005751 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5752 dump += StringPrintf(INDENT "FocusedApplications:\n");
5753 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5754 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005755 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005756 const std::chrono::duration timeout =
5757 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005758 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005759 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005760 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005763 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005765
Vishnu Nairc519ff72021-01-21 08:23:08 -08005766 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005767 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005769 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005770 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005771 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005772 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5773 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 }
5775 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005776 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
5778
arthurhung6d4bed92021-03-17 11:59:33 +08005779 if (mDragState) {
5780 dump += StringPrintf(INDENT "DragState:\n");
5781 mDragState->dump(dump, INDENT2);
5782 }
5783
Arthur Hungb92218b2018-08-14 12:00:21 +08005784 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005785 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5786 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5787 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5788 const auto& displayInfo = it->second;
5789 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5790 displayInfo.logicalHeight);
5791 displayInfo.transform.dump(dump, "transform", INDENT4);
5792 } else {
5793 dump += INDENT2 "No DisplayInfo found!\n";
5794 }
5795
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005796 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005797 dump += INDENT2 "Windows:\n";
5798 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005799 dump += StringPrintf(INDENT3 "%zu: %s", i,
5800 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005801 }
5802 } else {
5803 dump += INDENT2 "Windows: <none>\n";
5804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005807 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 }
5809
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005810 if (!mGlobalMonitorsByDisplay.empty()) {
5811 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5812 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005813 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005816 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005819 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820
5821 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005822 if (!mRecentQueue.empty()) {
5823 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005824 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005825 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005826 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005827 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005830 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832
5833 // Dump event currently being dispatched.
5834 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005835 dump += INDENT "PendingEvent:\n";
5836 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005837 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005838 dump += StringPrintf(", age=%" PRId64 "ms\n",
5839 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 }
5843
5844 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005845 if (!mInboundQueue.empty()) {
5846 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005847 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005848 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005849 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005850 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 }
5852 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005853 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 }
5855
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856 if (!mCommandQueue.empty()) {
5857 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5858 } else {
5859 dump += INDENT "CommandQueue: <empty>\n";
5860 }
5861
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005862 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005863 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005864 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08005865 dump += StringPrintf(INDENT2 "%i: channelName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005866 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005867 connection->inputPublisher.getChannel().getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005868 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005869 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005870 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005872 if (!connection->outboundQueue.empty()) {
5873 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5874 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005875 dump += dumpQueue(connection->outboundQueue, currentTime);
5876
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005878 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
5880
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005881 if (!connection->waitQueue.empty()) {
5882 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5883 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005884 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005886 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005888 std::string inputStateDump = streamableToString(connection->inputState);
5889 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005890 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005891 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 }
5894 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005895 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 }
5897
Antonio Kantek15beb512022-06-13 22:35:41 +00005898 if (!mTouchModePerDisplay.empty()) {
5899 dump += INDENT "TouchModePerDisplay:\n";
5900 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5901 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5902 std::to_string(touchMode).c_str());
5903 }
5904 } else {
5905 dump += INDENT "TouchModePerDisplay: <none>\n";
5906 }
5907
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005908 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005909 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5910 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5911 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005912 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005913 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005914 dump += INDENT "InputTracer: ";
5915 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916}
5917
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005918void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005919 const size_t numMonitors = monitors.size();
5920 for (size_t i = 0; i < numMonitors; i++) {
5921 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005922 const std::shared_ptr<Connection>& connection = monitor.connection;
5923 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005924 dump += "\n";
5925 }
5926}
5927
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005928class LooperEventCallback : public LooperCallback {
5929public:
5930 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5931 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5932
5933private:
5934 std::function<int(int events)> mCallback;
5935};
5936
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005937Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005938 if (DEBUG_CHANNEL_CREATION) {
5939 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005942 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005943 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005944 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005945
5946 if (result) {
5947 return base::Error(result) << "Failed to open input channel pair with name " << name;
5948 }
5949
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005951 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005952 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005953 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005954 std::shared_ptr<Connection> connection =
5955 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5956 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005958 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5959 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005960 ALOGE("Created a new connection, but the token %p is already known", token.get());
5961 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005962
5963 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5964 this, std::placeholders::_1, token);
5965
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005966 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005967 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 } // release lock
5969
5970 // Wake the looper because some connections have changed.
5971 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005972 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973}
5974
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005975Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005976 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005977 gui::Pid pid) {
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005978 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005979 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005980 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005981 if (result) {
5982 return base::Error(result) << "Failed to open input channel pair with name " << name;
5983 }
5984
Michael Wright3dd60e22019-03-27 22:06:44 +00005985 { // acquire lock
5986 std::scoped_lock _l(mLock);
5987
5988 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005989 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5990 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005991 }
5992
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005993 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005994 const int fd = serverChannel->getFd();
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08005995 std::shared_ptr<Connection> connection =
5996 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/true,
5997 mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005998
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005999 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
6000 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006001 ALOGE("Created a new connection, but the token %p is already known", token.get());
6002 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006003
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006004 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
6005 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00006006
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006007 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00006008
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006009 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006010 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00006011 }
Garfield Tan15601662020-09-22 15:32:38 -07006012
Michael Wright3dd60e22019-03-27 22:06:44 +00006013 // Wake the looper because some connections have changed.
6014 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006015 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006016}
6017
Garfield Tan15601662020-09-22 15:32:38 -07006018status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006020 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021
Harry Cutts33476232023-01-30 19:57:29 +00006022 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023 if (status) {
6024 return status;
6025 }
6026 } // release lock
6027
6028 // Wake the poll loop because removing the connection may have changed the current
6029 // synchronization state.
6030 mLooper->wake();
6031 return OK;
6032}
6033
Garfield Tan15601662020-09-22 15:32:38 -07006034status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6035 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006036 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006037 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006038 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 return BAD_VALUE;
6040 }
6041
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006042 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006043
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006045 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 }
6047
Siarhei Vishniakou7b9f4f52024-02-02 13:07:16 -08006048 mLooper->removeFd(connection->inputPublisher.getChannel().getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049
6050 nsecs_t currentTime = now();
6051 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6052
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006053 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054 return OK;
6055}
6056
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006057void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006058 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6059 auto& [displayId, monitors] = *it;
6060 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006061 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006062 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006063
Michael Wright3dd60e22019-03-27 22:06:44 +00006064 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006065 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006066 } else {
6067 ++it;
6068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 }
6070}
6071
Michael Wright3dd60e22019-03-27 22:06:44 +00006072status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006073 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006074 return pilferPointersLocked(token);
6075}
Michael Wright3dd60e22019-03-27 22:06:44 +00006076
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006077status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006078 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6079 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006080 LOG(WARNING)
6081 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006083 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006084
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006085 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006086 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006087 LOG(WARNING)
6088 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6089 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006090 return BAD_VALUE;
6091 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006092 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006093 if (deviceIds.empty()) {
6094 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006095 return BAD_VALUE;
6096 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006097
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006098 for (const DeviceId deviceId : deviceIds) {
6099 TouchState& state = *statePtr;
6100 TouchedWindow& window = *windowPtr;
6101 // Send cancel events to all the input channels we're stealing from.
6102 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6103 "input channel stole pointer stream");
6104 options.deviceId = deviceId;
6105 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006106 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6107 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006108 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006109
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006110 std::string canceledWindows;
6111 for (const TouchedWindow& w : state.windows) {
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006112 if (w.windowHandle->getToken() != token) {
6113 synthesizeCancelationEventsForWindowLocked(w.windowHandle, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006114 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006115 canceledWindows += w.windowHandle->getName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006116 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006117 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006118 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006119 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006120 << " is stealing input gesture for device " << deviceId << " from "
6121 << canceledWindows;
6122
6123 // Prevent the gesture from being sent to any other windows.
6124 // This only blocks relevant pointers to be sent to other windows
6125 window.addPilferingPointers(deviceId, pointerIds);
6126
6127 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006128 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006129 return OK;
6130}
6131
Prabir Pradhan99987712020-11-10 18:43:05 -08006132void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6133 { // acquire lock
6134 std::scoped_lock _l(mLock);
6135 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006136 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006137 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6138 windowHandle != nullptr ? windowHandle->getName().c_str()
6139 : "token without window");
6140 }
6141
Vishnu Nairc519ff72021-01-21 08:23:08 -08006142 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006143 if (focusedToken != windowToken) {
6144 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6145 enabled ? "enable" : "disable");
6146 return;
6147 }
6148
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006149 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006150 ALOGW("Ignoring request to %s Pointer Capture: "
6151 "window has %s requested pointer capture.",
6152 enabled ? "enable" : "disable", enabled ? "already" : "not");
6153 return;
6154 }
6155
Christine Franksb768bb42021-11-29 12:11:31 -08006156 if (enabled) {
6157 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6158 mIneligibleDisplaysForPointerCapture.end(),
6159 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6160 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6161 return;
6162 }
6163 }
6164
Prabir Pradhan99987712020-11-10 18:43:05 -08006165 setPointerCaptureLocked(enabled);
6166 } // release lock
6167
6168 // Wake the thread to process command entries.
6169 mLooper->wake();
6170}
6171
Christine Franksb768bb42021-11-29 12:11:31 -08006172void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6173 { // acquire lock
6174 std::scoped_lock _l(mLock);
6175 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6176 if (!isEligible) {
6177 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6178 }
6179 } // release lock
6180}
6181
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006182std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006183 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006184 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006185 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006186 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006187 }
6188 }
6189 }
6190 return std::nullopt;
6191}
6192
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006193std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6194 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006195 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006196 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006197 }
6198
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006199 for (const auto& [token, connection] : mConnectionsByToken) {
6200 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006201 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006202 }
6203 }
Robert Carr4e670e52018-08-15 13:26:12 -07006204
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006205 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206}
6207
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006208std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006209 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006210 if (connection == nullptr) {
6211 return "<nullptr>";
6212 }
6213 return connection->getInputChannelName();
6214}
6215
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006216void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006217 mAnrTracker.eraseToken(connection->getToken());
6218 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006219}
6220
Prabir Pradhancef936d2021-07-21 16:17:52 +00006221void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006222 const std::shared_ptr<Connection>& connection,
6223 uint32_t seq, bool handled,
6224 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006226 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006227
6228 { // Start critical section
6229 auto dispatchEntryIt =
6230 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6231 [seq](auto& e) { return e->seq == seq; });
6232 if (dispatchEntryIt == connection->waitQueue.end()) {
6233 return;
6234 }
6235
6236 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6237
6238 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6239 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006240 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getInputChannelName().c_str(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006241 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6242 }
6243 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006244 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006245 dispatchEntry.deliveryTime, consumeTime, finishTime);
6246 }
6247
6248 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006249 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6250 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006251 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006252 }
6253 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006254
6255 // Dequeue the event and start the next cycle.
6256 // Because the lock might have been released, it is possible that the
6257 // contents of the wait queue to have been drained, so we need to double-check
6258 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006259 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6260 [seq](auto& e) { return e->seq == seq; });
6261 if (entryIt != connection->waitQueue.end()) {
6262 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6263 connection->waitQueue.erase(entryIt);
6264
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006265 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6267 if (!connection->responsive) {
6268 connection->responsive = isConnectionResponsive(*connection);
6269 if (connection->responsive) {
6270 // The connection was unresponsive, and now it's responsive.
6271 processConnectionResponsiveLocked(*connection);
6272 }
6273 }
6274 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006275 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006276 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6277 // Only dispatch fallbacks if there is a window for the connection.
6278 if (windowHandle != nullptr) {
6279 const auto inputTarget =
6280 createInputTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
6281 dispatchEntry->targetFlags,
6282 fallbackKeyEntry->downTime);
6283 if (inputTarget.has_value()) {
6284 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry),
6285 *inputTarget);
6286 }
6287 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006289 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006290 }
6291
6292 // Start the next dispatch cycle for this connection.
6293 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294}
6295
Prabir Pradhancef936d2021-07-21 16:17:52 +00006296void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6297 const sp<IBinder>& newToken) {
6298 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6299 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006300 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 };
6302 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303}
6304
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6306 auto command = [this, token, x, y]() REQUIRES(mLock) {
6307 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006308 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309 };
6310 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006311}
6312
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006313void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006314 if (connection == nullptr) {
6315 LOG_ALWAYS_FATAL("Caller must check for nullness");
6316 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006317 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6318 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006319 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006321 connection->getInputChannelName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006322 return;
6323 }
6324 /**
6325 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6326 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6327 * has changed. This could cause newer entries to time out before the already dispatched
6328 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6329 * processes the events linearly. So providing information about the oldest entry seems to be
6330 * most useful.
6331 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006332 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6333 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006334 std::string reason =
6335 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006336 connection->getInputChannelName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006337 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006338 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006339 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006340 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006341
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006342 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6343
6344 // Stop waking up for events on this connection, it is already unresponsive
6345 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006346}
6347
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006348void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6349 std::string reason =
6350 StringPrintf("%s does not have a focused window", application->getName().c_str());
6351 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006352
Yabin Cui8eb9c552023-06-08 18:05:07 +00006353 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006354 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006355 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356 };
6357 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006358}
6359
chaviw98318de2021-05-19 16:45:23 -05006360void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006361 const std::string& reason) {
6362 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6363 updateLastAnrStateLocked(windowLabel, reason);
6364}
6365
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006366void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6367 const std::string& reason) {
6368 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006369 updateLastAnrStateLocked(windowLabel, reason);
6370}
6371
6372void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6373 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006375 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 struct tm tm;
6377 localtime_r(&t, &tm);
6378 char timestr[64];
6379 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006380 mLastAnrState.clear();
6381 mLastAnrState += INDENT "ANR:\n";
6382 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006383 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6384 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006385 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386}
6387
Prabir Pradhancef936d2021-07-21 16:17:52 +00006388void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006389 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006390 const KeyEvent event = createKeyEvent(entry);
6391 nsecs_t delay = 0;
6392 { // release lock
6393 scoped_unlock unlock(mLock);
6394 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006395 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006396 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6397 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6398 std::to_string(t.duration().count()).c_str());
6399 }
6400 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401
6402 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006403 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006405 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006407 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006408 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410}
6411
Prabir Pradhancef936d2021-07-21 16:17:52 +00006412void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006413 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006414 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006415 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006416 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006417 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006418 };
6419 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006420}
6421
Prabir Pradhanedd96402022-02-15 01:46:16 -08006422void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006423 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006424 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006425 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006426 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006427 };
6428 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006429}
6430
6431/**
6432 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6433 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6434 * command entry to the command queue.
6435 */
6436void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6437 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006438 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006439 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006440 if (connection.monitor) {
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006441 ALOGW("Monitor %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006442 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006443 pid = findMonitorPidByTokenLocked(connectionToken);
6444 } else {
6445 // The connection is a window
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006446 ALOGW("Window %s is unresponsive: %s", connection.getInputChannelName().c_str(),
Prabir Pradhanedd96402022-02-15 01:46:16 -08006447 reason.c_str());
6448 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6449 if (handle != nullptr) {
6450 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006451 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006452 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006453 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006454}
6455
6456/**
6457 * Tell the policy that a connection has become responsive so that it can stop ANR.
6458 */
6459void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006460 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006461 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006462 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006463 pid = findMonitorPidByTokenLocked(connectionToken);
6464 } else {
6465 // The connection is a window
6466 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6467 if (handle != nullptr) {
6468 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006469 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006470 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006471 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006472}
6473
Prabir Pradhan24047542023-11-02 17:14:59 +00006474std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006475 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006476 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006477 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006478 if (!handled) {
6479 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006480 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006481 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006482 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 // Get the fallback key state.
6486 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006487 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006488 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006489 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 connection->inputState.removeFallbackKey(originalKeyCode);
6491 }
6492
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006493 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006494 // If the application handles the original key for which we previously
6495 // generated a fallback or if the window is not a foreground window,
6496 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006497 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006499 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6500 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6501 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6502 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6503 keyEntry.policyFlags);
6504 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006505 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006506 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507
6508 mLock.unlock();
6509
Prabir Pradhana41d2442023-04-20 21:30:40 +00006510 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006511 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6512 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006513 unhandledKeyFallback) {
6514 event = *unhandledKeyFallback;
6515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516
6517 mLock.lock();
6518
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006519 // Cancel the fallback key, but only if we still have a window for the channel.
6520 // It could have been removed during the policy call.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006521 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006522 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6523 if (windowHandle != nullptr) {
6524 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6525 "application handled the original non-fallback key "
6526 "or is no longer a foreground target, "
6527 "canceling previously dispatched fallback key");
6528 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006529 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006532 connection->inputState.removeFallbackKey(originalKeyCode);
6533 }
6534 } else {
6535 // If the application did not handle a non-fallback key, first check
6536 // that we are in a good state to perform unhandled key event processing
6537 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006538 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006539 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006540 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6541 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6542 "since this is not an initial down. "
6543 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6544 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6545 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006546 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006549 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6551 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6552 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6553 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6554 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006555 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556
6557 mLock.unlock();
6558
Prabir Pradhana41d2442023-04-20 21:30:40 +00006559 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006560 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6561 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006562 fb) {
6563 fallback = true;
6564 event = *fb;
6565 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006566
6567 mLock.lock();
6568
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006569 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006570 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006571 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006572 }
6573
6574 // Latch the fallback keycode for this key on an initial down.
6575 // The fallback keycode cannot change at any other point in the lifecycle.
6576 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006578 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006580 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006582 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583 }
6584
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006585 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006586
6587 // Cancel the fallback key if the policy decides not to send it anymore.
6588 // We will continue to dispatch the key to the policy but we will no
6589 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006590 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6591 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6593 if (fallback) {
6594 ALOGD("Unhandled key event: Policy requested to send key %d"
6595 "as a fallback for %d, but on the DOWN it had requested "
6596 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006597 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006598 } else {
6599 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6600 "but on the DOWN it had requested to send %d. "
6601 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006602 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006603 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006604 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006605
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006606 const auto windowHandle = getWindowHandleLocked(connection->getToken());
6607 if (windowHandle != nullptr) {
6608 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
6609 "canceling fallback, policy no longer desires it");
6610 options.keyCode = *fallbackKeyCode;
Prabir Pradhanbb3f1c02024-01-04 20:17:14 +00006611 synthesizeCancelationEventsForWindowLocked(windowHandle, options, connection);
Prabir Pradhanfa2c69f2024-02-01 20:31:34 +00006612 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006613
6614 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006615 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006616 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006617 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006618 }
6619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006621 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6622 {
6623 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006624 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006625 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006626 for (const auto& [key, value] : fallbackKeys) {
6627 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006628 }
6629 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6630 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006632 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006633
6634 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006635 // Return the fallback key that we want dispatched to the channel.
6636 std::unique_ptr<KeyEntry> newEntry =
6637 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6638 event.getEventTime(), event.getDeviceId(),
6639 event.getSource(), event.getDisplayId(),
6640 keyEntry.policyFlags, keyEntry.action,
6641 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6642 *fallbackKeyCode, event.getScanCode(),
6643 event.getMetaState(), event.getRepeatCount(),
6644 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006645 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6646 ALOGD("Unhandled key event: Dispatching fallback key. "
6647 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006648 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006649 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006650 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006651 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006652 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6653 ALOGD("Unhandled key event: No fallback key.");
6654 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006655
6656 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006657 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658 }
6659 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006660 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006661}
6662
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663void InputDispatcher::traceInboundQueueLengthLocked() {
6664 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006665 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666 }
6667}
6668
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006669void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670 if (ATRACE_ENABLED()) {
6671 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006672 snprintf(counterName, sizeof(counterName), "oq:%s",
6673 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006674 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675 }
6676}
6677
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006678void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006679 if (ATRACE_ENABLED()) {
6680 char counterName[40];
Siarhei Vishniakou10bfdc92024-02-01 11:12:57 -08006681 snprintf(counterName, sizeof(counterName), "wq:%s",
6682 connection.getInputChannelName().c_str());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006683 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006684 }
6685}
6686
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006687void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006688 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006689
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006690 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006691 dumpDispatchStateLocked(dump);
6692
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006693 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006694 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006695 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006696 }
6697}
6698
6699void InputDispatcher::monitor() {
6700 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006701 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006703 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704}
6705
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006706/**
6707 * Wake up the dispatcher and wait until it processes all events and commands.
6708 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6709 * this method can be safely called from any thread, as long as you've ensured that
6710 * the work you are interested in completing has already been queued.
6711 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006712bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006713 /**
6714 * Timeout should represent the longest possible time that a device might spend processing
6715 * events and commands.
6716 */
6717 constexpr std::chrono::duration TIMEOUT = 100ms;
6718 std::unique_lock lock(mLock);
6719 mLooper->wake();
6720 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6721 return result == std::cv_status::no_timeout;
6722}
6723
Vishnu Naire798b472020-07-23 13:52:21 -07006724/**
6725 * Sets focus to the window identified by the token. This must be called
6726 * after updating any input window handles.
6727 *
6728 * Params:
6729 * request.token - input channel token used to identify the window that should gain focus.
6730 * request.focusedToken - the token that the caller expects currently to be focused. If the
6731 * specified token does not match the currently focused window, this request will be dropped.
6732 * If the specified focused token matches the currently focused window, the call will succeed.
6733 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6734 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6735 * when requesting the focus change. This determines which request gets
6736 * precedence if there is a focus change request from another source such as pointer down.
6737 */
Vishnu Nair958da932020-08-21 17:12:37 -07006738void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6739 { // acquire lock
6740 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006741 std::optional<FocusResolver::FocusChanges> changes =
6742 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6743 if (changes) {
6744 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006745 }
6746 } // release lock
6747 // Wake up poll loop since it may need to make new input dispatching choices.
6748 mLooper->wake();
6749}
6750
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006751void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes,
6752 const sp<WindowInfoHandle> removedFocusedWindowHandle) {
Vishnu Nairc519ff72021-01-21 08:23:08 -08006753 if (changes.oldFocus) {
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006754 const auto resolvedWindow = removedFocusedWindowHandle != nullptr
6755 ? removedFocusedWindowHandle
6756 : getWindowHandleLocked(changes.oldFocus, changes.displayId);
6757 if (resolvedWindow == nullptr) {
6758 LOG(FATAL) << __func__ << ": Previously focused token did not have a window";
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006759 }
Prabir Pradhan4b9b1a12024-02-02 00:16:17 +00006760 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
6761 "focus left window");
6762 synthesizeCancelationEventsForWindowLocked(resolvedWindow, options);
6763 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006764 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006765 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006766 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006767 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006768 }
6769
Prabir Pradhan99987712020-11-10 18:43:05 -08006770 // If a window has pointer capture, then it must have focus. We need to ensure that this
6771 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6772 // If the window loses focus before it loses pointer capture, then the window can be in a state
6773 // where it has pointer capture but not focus, violating the contract. Therefore we must
6774 // dispatch the pointer capture event before the focus event. Since focus events are added to
6775 // the front of the queue (above), we add the pointer capture event to the front of the queue
6776 // after the focus events are added. This ensures the pointer capture event ends up at the
6777 // front.
6778 disablePointerCaptureForcedLocked();
6779
Vishnu Nairc519ff72021-01-21 08:23:08 -08006780 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006781 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006782 }
6783}
Vishnu Nair958da932020-08-21 17:12:37 -07006784
Prabir Pradhan99987712020-11-10 18:43:05 -08006785void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006786 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006787 return;
6788 }
6789
6790 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6791
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006792 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006793 setPointerCaptureLocked(false);
6794 }
6795
6796 if (!mWindowTokenWithPointerCapture) {
6797 // No need to send capture changes because no window has capture.
6798 return;
6799 }
6800
6801 if (mPendingEvent != nullptr) {
6802 // Move the pending event to the front of the queue. This will give the chance
6803 // for the pending event to be dropped if it is a captured event.
6804 mInboundQueue.push_front(mPendingEvent);
6805 mPendingEvent = nullptr;
6806 }
6807
6808 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006809 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006810 mInboundQueue.push_front(std::move(entry));
6811}
6812
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006813void InputDispatcher::setPointerCaptureLocked(bool enable) {
6814 mCurrentPointerCaptureRequest.enable = enable;
6815 mCurrentPointerCaptureRequest.seq++;
6816 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006817 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006818 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006819 };
6820 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006821}
6822
Vishnu Nair599f1412021-06-21 10:39:58 -07006823void InputDispatcher::displayRemoved(int32_t displayId) {
6824 { // acquire lock
6825 std::scoped_lock _l(mLock);
6826 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006827 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006828 setFocusedApplicationLocked(displayId, nullptr);
6829 // Call focus resolver to clean up stale requests. This must be called after input windows
6830 // have been removed for the removed display.
6831 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006832 // Reset pointer capture eligibility, regardless of previous state.
6833 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006834 // Remove the associated touch mode state.
6835 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006836 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006837 } // release lock
6838
6839 // Wake up poll loop since it may need to make new input dispatching choices.
6840 mLooper->wake();
6841}
6842
Patrick Williamsd828f302023-04-28 17:52:08 -05006843void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006844 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6845 {
6846 // acquire lock
6847 std::scoped_lock _l(mLock);
6848 logDispatchStateLocked();
6849 }
6850 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6851 result.error().message().c_str());
6852 };
chaviw15fab6f2021-06-07 14:15:52 -05006853 // The listener sends the windows as a flattened array. Separate the windows by display for
6854 // more convenient parsing.
6855 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006856 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006857 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006858 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006859 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006860
6861 { // acquire lock
6862 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006863
6864 // Ensure that we have an entry created for all existing displays so that if a displayId has
6865 // no windows, we can tell that the windows were removed from the display.
6866 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6867 handlesPerDisplay[displayId];
6868 }
6869
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006870 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006871 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006872 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6873 }
6874
6875 for (const auto& [displayId, handles] : handlesPerDisplay) {
6876 setInputWindowsLocked(handles, displayId);
6877 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006878
6879 if (update.vsyncId < mWindowInfosVsyncId) {
6880 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6881 ", current update vsync id: %" PRId64,
6882 mWindowInfosVsyncId, update.vsyncId);
6883 }
6884 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006885 }
6886 // Wake up poll loop since it may need to make new input dispatching choices.
6887 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006888}
6889
Vishnu Nair062a8672021-09-03 16:07:44 -07006890bool InputDispatcher::shouldDropInput(
6891 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006892 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6893 (windowHandle->getInfo()->inputConfig.test(
6894 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006895 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006896 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6897 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006898 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006899 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006900 windowHandle->getInfo()->displayId);
6901 return true;
6902 }
6903 return false;
6904}
6905
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006906void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006907 const gui::WindowInfosUpdate& update) {
6908 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006909}
6910
Arthur Hungdfd528e2021-12-08 13:23:04 +00006911void InputDispatcher::cancelCurrentTouch() {
6912 {
6913 std::scoped_lock _l(mLock);
6914 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006915 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006916 "cancel current touch");
6917 synthesizeCancelationEventsForAllConnectionsLocked(options);
6918
6919 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006920 }
6921 // Wake up poll loop since there might be work to do.
6922 mLooper->wake();
6923}
6924
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006925void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6926 std::scoped_lock _l(mLock);
6927 mMonitorDispatchingTimeout = timeout;
6928}
6929
Arthur Hungc539dbb2022-12-08 07:45:36 +00006930void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6931 const sp<WindowInfoHandle>& oldWindowHandle,
6932 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006933 TouchState& state, int32_t deviceId,
6934 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006935 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006936 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006937 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6938 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6939 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6940 newWindowHandle->getInfo()->inputConfig.test(
6941 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6942 const sp<WindowInfoHandle> oldWallpaper =
6943 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6944 const sp<WindowInfoHandle> newWallpaper =
6945 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6946 if (oldWallpaper == newWallpaper) {
6947 return;
6948 }
6949
6950 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006951 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006952 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006953 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006954 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006955 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006956 }
6957
6958 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006959 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6960 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006961 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006962 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006963 }
6964}
6965
6966void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6967 ftl::Flags<InputTarget::Flags> newTargetFlags,
6968 const sp<WindowInfoHandle> fromWindowHandle,
6969 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006970 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006971 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006972 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6973 fromWindowHandle->getInfo()->inputConfig.test(
6974 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6975 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6976 toWindowHandle->getInfo()->inputConfig.test(
6977 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6978
6979 const sp<WindowInfoHandle> oldWallpaper =
6980 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6981 const sp<WindowInfoHandle> newWallpaper =
6982 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6983 if (oldWallpaper == newWallpaper) {
6984 return;
6985 }
6986
6987 if (oldWallpaper != nullptr) {
6988 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6989 "transferring touch focus to another window");
6990 state.removeWindowByToken(oldWallpaper->getToken());
6991 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6992 }
6993
6994 if (newWallpaper != nullptr) {
6995 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006996 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006997 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6998 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006999 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08007000 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007001 std::shared_ptr<Connection> wallpaperConnection =
7002 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007003 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07007004 std::shared_ptr<Connection> toConnection =
7005 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00007006 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
7007 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
7008 wallpaperFlags);
7009 }
7010 }
7011}
7012
7013sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
7014 const sp<WindowInfoHandle>& windowHandle) const {
7015 const std::vector<sp<WindowInfoHandle>>& windowHandles =
7016 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
7017 bool foundWindow = false;
7018 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
7019 if (!foundWindow && otherHandle != windowHandle) {
7020 continue;
7021 }
7022 if (windowHandle == otherHandle) {
7023 foundWindow = true;
7024 continue;
7025 }
7026
7027 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
7028 return otherHandle;
7029 }
7030 }
7031 return nullptr;
7032}
7033
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007034void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7035 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007036 std::scoped_lock _l(mLock);
7037
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007038 mConfig.keyRepeatTimeout = timeout.count();
7039 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007040}
7041
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007042bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7043 DeviceId deviceId, int32_t pointerId) {
7044 std::scoped_lock _l(mLock);
7045 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7046 if (touchStateIt == mTouchStatesByDisplay.end()) {
7047 return false;
7048 }
7049 for (const TouchedWindow& window : touchStateIt->second.windows) {
7050 if (window.windowHandle->getToken() == token &&
7051 (window.hasTouchingPointer(deviceId, pointerId) ||
7052 window.hasHoveringPointer(deviceId, pointerId))) {
7053 return true;
7054 }
7055 }
7056 return false;
7057}
7058
Garfield Tane84e6f92019-08-29 17:28:41 -07007059} // namespace android::inputdispatcher