blob: d706c4d1b704abadaee084aa95150c2b50cc5ba2 [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
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700124// Additional key latency in case a connection is still processing some motion events.
125// This will help with the case when a user touched a button that opens a new window,
126// and gives us the chance to dispatch the key to this new window.
127constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000130constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
131
Antonio Kantekea47acb2021-12-23 12:41:25 -0800132// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000133constexpr int LOGTAG_INPUT_INTERACTION = 62000;
134constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000135constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000136
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000137const ui::Transform kIdentityTransform;
138
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000139inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 return systemTime(SYSTEM_TIME_MONOTONIC);
141}
142
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700143inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000144 if (binder == nullptr) {
145 return "<null>";
146 }
147 return StringPrintf("%p", binder.get());
148}
149
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000150static std::string uidString(const gui::Uid& uid) {
151 return uid.toString();
152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AKEY_EVENT_ACTION_DOWN:
157 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700158 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700159 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700160 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 }
162}
163
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164Result<void> validateKeyEvent(int32_t action) {
165 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166}
167
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800169 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700171 case AMOTION_EVENT_ACTION_UP: {
172 if (pointerCount != 1) {
173 return Error() << "invalid pointer count " << pointerCount;
174 }
175 return {};
176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_HOVER_ENTER:
179 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700180 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
181 if (pointerCount < 1) {
182 return Error() << "invalid pointer count " << pointerCount;
183 }
184 return {};
185 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800186 case AMOTION_EVENT_ACTION_CANCEL:
187 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700189 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 case AMOTION_EVENT_ACTION_POINTER_DOWN:
191 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800192 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193 if (index < 0) {
194 return Error() << "invalid index " << index << " for "
195 << MotionEvent::actionToString(action);
196 }
197 if (index >= pointerCount) {
198 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
199 }
200 if (pointerCount <= 1) {
201 return Error() << "invalid pointer count " << pointerCount << " for "
202 << MotionEvent::actionToString(action);
203 }
204 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700205 }
206 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
208 if (actionButton == 0) {
209 return Error() << "action button should be nonzero for "
210 << MotionEvent::actionToString(action);
211 }
212 return {};
213 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700215 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217}
218
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000219int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500220 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
221}
222
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
224 const PointerProperties* pointerProperties) {
225 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
226 if (!actionCheck.ok()) {
227 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
229 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700230 return Error() << "Motion event has invalid pointer count " << pointerCount
231 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800233 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 for (size_t i = 0; i < pointerCount; i++) {
235 int32_t id = pointerProperties[i].id;
236 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700237 return Error() << "Motion event has invalid pointer id " << id
238 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800240 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700241 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800243 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700245 return {};
246}
247
248Result<void> validateInputEvent(const InputEvent& event) {
249 switch (event.getType()) {
250 case InputEventType::KEY: {
251 const KeyEvent& key = static_cast<const KeyEvent&>(event);
252 const int32_t action = key.getAction();
253 return validateKeyEvent(action);
254 }
255 case InputEventType::MOTION: {
256 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
257 const int32_t action = motion.getAction();
258 const size_t pointerCount = motion.getPointerCount();
259 const PointerProperties* pointerProperties = motion.getPointerProperties();
260 const int32_t actionButton = motion.getActionButton();
261 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
262 }
263 default: {
264 return {};
265 }
266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267}
268
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800269std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
270 std::bitset<MAX_POINTER_ID + 1> pointerIds;
271 for (const PointerProperties& pointer : pointers) {
272 pointerIds.set(pointer.id);
273 }
274 return pointerIds;
275}
276
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000277std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000279 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 }
281
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000282 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 bool first = true;
284 Region::const_iterator cur = region.begin();
285 Region::const_iterator const tail = region.end();
286 while (cur != tail) {
287 if (first) {
288 first = false;
289 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800290 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800292 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800293 cur++;
294 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000295 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296}
297
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000298std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
299 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500300 constexpr size_t maxEntries = 50; // max events to print
301 constexpr size_t skipBegin = maxEntries / 2;
302 const size_t skipEnd = queue.size() - maxEntries / 2;
303 // skip from maxEntries / 2 ... size() - maxEntries/2
304 // only print from 0 .. skipBegin and then from skipEnd .. size()
305
306 std::string dump;
307 for (size_t i = 0; i < queue.size(); i++) {
308 const DispatchEntry& entry = *queue[i];
309 if (i >= skipBegin && i < skipEnd) {
310 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
311 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
312 continue;
313 }
314 dump.append(INDENT4);
315 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000316 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
317 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500318 ns2ms(currentTime - entry.eventEntry->eventTime));
319 if (entry.deliveryTime != 0) {
320 // This entry was delivered, so add information on how long we've been waiting
321 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
322 }
323 dump.append("\n");
324 }
325 return dump;
326}
327
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700328/**
329 * Find the entry in std::unordered_map by key, and return it.
330 * If the entry is not found, return a default constructed entry.
331 *
332 * Useful when the entries are vectors, since an empty vector will be returned
333 * if the entry is not found.
334 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
335 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700336template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700338 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700339 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800340}
341
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700343 if (first == second) {
344 return true;
345 }
346
347 if (first == nullptr || second == nullptr) {
348 return false;
349 }
350
351 return first->getToken() == second->getToken();
352}
353
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000354bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000355 if (first == nullptr || second == nullptr) {
356 return false;
357 }
358 return first->applicationInfo.token != nullptr &&
359 first->applicationInfo.token == second->applicationInfo.token;
360}
361
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800362template <typename T>
363size_t firstMarkedBit(T set) {
364 // TODO: replace with std::countr_zero from <bit> when that's available
365 LOG_ALWAYS_FATAL_IF(set.none());
366 size_t i = 0;
367 while (!set.test(i)) {
368 i++;
369 }
370 return i;
371}
372
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000373std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
374 std::shared_ptr<const EventEntry> eventEntry,
375 ftl::Flags<InputTarget::Flags> inputTargetFlags,
376 int64_t vsyncId) {
377 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
378 const std::optional<int32_t> windowId =
379 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
380 // Assume the only targets that are not associated with a window are global monitors, and use
381 // the system UID for global monitors for tracing purposes.
382 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
chaviw1ff3d1e2020-07-01 15:53:47 -0700383 if (inputTarget.useDefaultPointerTransform()) {
384 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700385 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700386 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000387 inputTarget.globalScaleFactor, uid, vsyncId,
388 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 }
390
391 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
392 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700395 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000396
397 // Use the first pointer information to normalize all other pointers. This could be any pointer
398 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700399 // uses the transform for the normalized pointer.
400 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800401 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700402 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700405 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000406 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
407 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700408 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409
410 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700411 // First, apply the current pointer's transform to update the coordinates into
412 // window space.
413 pointerCoords[pointerIndex].transform(currTransform);
414 // Next, apply the inverse transform of the normalized coordinates so the
415 // current coordinates are transformed into the normalized coordinate space.
416 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000417 }
418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700419 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000420 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
421 motionEntry.eventTime, motionEntry.deviceId,
422 motionEntry.source, motionEntry.displayId,
423 motionEntry.policyFlags, motionEntry.action,
424 motionEntry.actionButton, motionEntry.flags,
425 motionEntry.metaState, motionEntry.buttonState,
426 motionEntry.classification, motionEntry.edgeFlags,
427 motionEntry.xPrecision, motionEntry.yPrecision,
428 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
429 motionEntry.downTime, motionEntry.pointerProperties,
430 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431
432 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700433 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700434 firstPointerTransform, inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000435 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000436 return dispatchEntry;
437}
438
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
440 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700441 std::unique_ptr<InputChannel> uniqueServerChannel;
442 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
443
444 serverChannel = std::move(uniqueServerChannel);
445 return result;
446}
447
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500448template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000449bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500450 if (lhs == nullptr && rhs == nullptr) {
451 return true;
452 }
453 if (lhs == nullptr || rhs == nullptr) {
454 return false;
455 }
456 return *lhs == *rhs;
457}
458
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000459KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000460 KeyEvent event;
461 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
462 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
463 entry.repeatCount, entry.downTime, entry.eventTime);
464 return event;
465}
466
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000467bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 // Do not keep track of gesture monitors. They receive every event and would disproportionately
469 // affect the statistics.
470 if (connection.monitor) {
471 return false;
472 }
473 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
474 if (!connection.responsive) {
475 return false;
476 }
477 return true;
478}
479
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000480bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000481 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
482 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000483 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
484 return false;
485 }
486 // Only track latency for events that originated from hardware
487 if (eventEntry.isSynthesized()) {
488 return false;
489 }
490 const EventEntry::Type& inputEventEntryType = eventEntry.type;
491 if (inputEventEntryType == EventEntry::Type::KEY) {
492 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
493 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
494 return false;
495 }
496 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
497 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
498 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
499 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
500 return false;
501 }
502 } else {
503 // Not a key or a motion
504 return false;
505 }
506 if (!shouldReportMetricsForConnection(connection)) {
507 return false;
508 }
509 return true;
510}
511
Prabir Pradhancef936d2021-07-21 16:17:52 +0000512/**
513 * Connection is responsive if it has no events in the waitQueue that are older than the
514 * current time.
515 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000516bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000517 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000518 for (const auto& dispatchEntry : connection.waitQueue) {
519 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000520 return false;
521 }
522 }
523 return true;
524}
525
Antonio Kantekf16f2832021-09-28 04:39:20 +0000526// Returns true if the event type passed as argument represents a user activity.
527bool isUserActivityEvent(const EventEntry& eventEntry) {
528 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000529 case EventEntry::Type::CONFIGURATION_CHANGED:
530 case EventEntry::Type::DEVICE_RESET:
531 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000532 case EventEntry::Type::FOCUS:
533 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000534 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000535 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000536 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000537 case EventEntry::Type::KEY:
538 case EventEntry::Type::MOTION:
539 return true;
540 }
541}
542
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800543// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000544bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000545 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800546 const auto inputConfig = windowInfo.inputConfig;
547 if (windowInfo.displayId != displayId ||
548 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800549 return false;
550 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800552 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800553 return false;
554 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000555
556 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
557 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
558 // the window. Points on the right and bottom edges should not be inside the window, so we need
559 // to be careful about performing a hit test when the display is rotated, since the "right" and
560 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
561 // logical display in which WM determined the bounds. Perform the hit test in the logical
562 // display space to ensure these edges are considered correctly in all orientations.
563 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
564 const auto p = displayTransform.transform(x, y);
565 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800566 return false;
567 }
568 return true;
569}
570
Prabir Pradhand65552b2021-10-07 11:23:50 -0700571bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
572 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000573 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700574}
575
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800576// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000577// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
578// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
579// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800580// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000581bool canReceiveForegroundTouches(const WindowInfo& info) {
582 // A non-touchable window can still receive touch events (e.g. in the case of
583 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
584 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
585}
586
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000587bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700588 if (windowHandle == nullptr) {
589 return false;
590 }
591 const WindowInfo* windowInfo = windowHandle->getInfo();
592 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
593 return true;
594 }
595 return false;
596}
597
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598// Checks targeted injection using the window's owner's uid.
599// Returns an empty string if an entry can be sent to the given window, or an error message if the
600// entry is a targeted injection whose uid target doesn't match the window owner.
601std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
602 const EventEntry& entry) {
603 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
604 // The event was not injected, or the injected event does not target a window.
605 return {};
606 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000607 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000608 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000609 return StringPrintf("No valid window target for injection into uid %s.",
610 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000611 }
612 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000613 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
614 "owned by uid %s.",
615 uid.toString().c_str(), window->getName().c_str(),
616 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000617 }
618 return {};
619}
620
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000621std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700622 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
623 // Always dispatch mouse events to cursor position.
624 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000625 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700626 }
627
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700628 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000629 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
630 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700631}
632
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700633std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
634 if (eventEntry.type == EventEntry::Type::KEY) {
635 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
636 return keyEntry.downTime;
637 } else if (eventEntry.type == EventEntry::Type::MOTION) {
638 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
639 return motionEntry.downTime;
640 }
641 return std::nullopt;
642}
643
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000644/**
645 * Compare the old touch state to the new touch state, and generate the corresponding touched
646 * windows (== input targets).
647 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
648 * If the pointer just entered the new window, produce HOVER_ENTER.
649 * For pointers remaining in the window, produce HOVER_MOVE.
650 */
651std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
652 const TouchState& newTouchState,
653 const MotionEntry& entry) {
654 std::vector<TouchedWindow> out;
655 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700656
657 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
658 // ACTION_SCROLL events should not affect the hovering pointer dispatch
659 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 }
661
662 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800663 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000664
665 std::set<sp<WindowInfoHandle>> oldWindows;
666 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800667 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000668 }
669
670 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800671 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000672
673 // If the pointer is no longer in the new window set, send HOVER_EXIT.
674 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
675 if (newWindows.find(oldWindow) == newWindows.end()) {
676 TouchedWindow touchedWindow;
677 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000678 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000679 out.push_back(touchedWindow);
680 }
681 }
682
683 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
684 TouchedWindow touchedWindow;
685 touchedWindow.windowHandle = newWindow;
686 if (oldWindows.find(newWindow) == oldWindows.end()) {
687 // Any windows that have this pointer now, and didn't have it before, should get
688 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000689 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000690 } else {
691 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700692 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700693 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000694 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
695 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700696 // The Accessibility injected touch exploration event stream
697 // has known inconsistencies, so log ERROR instead of
698 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700699 severity = android::base::LogSeverity::ERROR;
700 }
701 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700702 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000703 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000704 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800705 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000706 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
707 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
708 }
709 out.push_back(touchedWindow);
710 }
711 return out;
712}
713
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800714template <typename T>
715std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
716 left.insert(left.end(), right.begin(), right.end());
717 return left;
718}
719
Harry Cuttsb166c002023-05-09 13:06:05 +0000720// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
721// both.
722void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
723 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
724 if (!window.windowHandle->getInfo()->inputConfig.test(
725 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
726 // In addition to TouchState, erase this window from the input targets! We don't have a
727 // good way to do this today except by adding a nested loop.
728 // TODO(b/282025641): simplify this code once InputTargets are being identified
729 // separately from TouchedWindows.
730 std::erase_if(targets, [&](const InputTarget& target) {
731 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
732 });
733 return true;
734 }
735 return false;
736 });
737}
738
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700739/**
740 * In general, touch should be always split between windows. Some exceptions:
741 * 1. Don't split touch if all of the below is true:
742 * (a) we have an active pointer down *and*
743 * (b) a new pointer is going down that's from the same device *and*
744 * (c) the window that's receiving the current pointer does not support split touch.
745 * 2. Don't split mouse events
746 */
747bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
748 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
749 // We should never split mouse events
750 return false;
751 }
752 for (const TouchedWindow& touchedWindow : touchState.windows) {
753 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
754 // Spy windows should not affect whether or not touch is split.
755 continue;
756 }
757 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
758 continue;
759 }
760 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
761 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
762 // Wallpaper window should not affect whether or not touch is split
763 continue;
764 }
765
766 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
767 return false;
768 }
769 }
770 return true;
771}
772
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700773/**
774 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
775 */
776bool isStylusActiveInDisplay(
777 int32_t displayId,
778 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
779 const auto it = touchStatesByDisplay.find(displayId);
780 if (it == touchStatesByDisplay.end()) {
781 return false;
782 }
783 const TouchState& state = it->second;
784 return state.hasActiveStylus();
785}
786
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800787Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
788 struct HashFunction {
789 size_t operator()(const WindowInfo& info) const { return info.id; }
790 };
791
792 std::unordered_set<WindowInfo, HashFunction> windowSet;
793 for (const WindowInfo& info : update.windowInfos) {
794 const auto [_, inserted] = windowSet.insert(info);
795 if (!inserted) {
796 return Error() << "Duplicate entry for " << info;
797 }
798 }
799 return {};
800}
801
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800802int32_t getUserActivityEventType(const EventEntry& eventEntry) {
803 switch (eventEntry.type) {
804 case EventEntry::Type::KEY: {
805 return USER_ACTIVITY_EVENT_BUTTON;
806 }
807 case EventEntry::Type::MOTION: {
808 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
809 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
810 return USER_ACTIVITY_EVENT_TOUCH;
811 }
812 return USER_ACTIVITY_EVENT_OTHER;
813 }
814 default: {
815 LOG_ALWAYS_FATAL("%s events are not user activity",
816 ftl::enum_string(eventEntry.type).c_str());
817 }
818 }
819}
820
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000821} // namespace
822
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823// --- InputDispatcher ---
824
Prabir Pradhana41d2442023-04-20 21:30:40 +0000825InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000826 : InputDispatcher(policy,
827 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
828 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000829
830InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
831 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700832 : mPolicy(policy),
833 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800835 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800836 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700837 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800838 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700839 mDispatchEnabled(false),
840 mDispatchFrozen(false),
841 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100842 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000843 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800844 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000845 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000846 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700847 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800848 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700850 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700851#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700852 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700853#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700854 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000855
856 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000857 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000858 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800859
860 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861}
862
863InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
Prabir Pradhancef936d2021-07-21 16:17:52 +0000866 resetKeyRepeatLocked();
867 releasePendingEventLocked();
868 drainInboundQueueLocked();
869 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000871 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700872 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000873 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875}
876
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700877status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700878 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700879 return ALREADY_EXISTS;
880 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700881 mThread = std::make_unique<InputThread>(
882 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
883 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700884}
885
886status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700887 if (mThread && mThread->isCallingThread()) {
888 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700889 return INVALID_OPERATION;
890 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700891 mThread.reset();
892 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700896 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800898 std::scoped_lock _l(mLock);
899 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 // Run a dispatch loop if there are no pending commands.
902 // The dispatch loop might enqueue commands to run afterwards.
903 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800904 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 // Run all pending commands if there are any.
908 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000909 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700910 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913 // If we are still waiting for ack on some events,
914 // we might have to wake up earlier to check if an app is anr'ing.
915 const nsecs_t nextAnrCheck = processAnrsLocked();
916 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
917
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800918 // We are about to enter an infinitely long sleep, because we have no commands or
919 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700920 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800921 mDispatcherEnteredIdle.notify_all();
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 } // release lock
924
925 // Wait for callback or timeout or wake. (make sure we round up, not down)
926 nsecs_t currentTime = now();
927 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
928 mLooper->pollOnce(timeoutMillis);
929}
930
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500932 * Raise ANR if there is no focused window.
933 * Before the ANR is raised, do a final state check:
934 * 1. The currently focused application must be the same one we are waiting for.
935 * 2. Ensure we still don't have a focused window.
936 */
937void InputDispatcher::processNoFocusedWindowAnrLocked() {
938 // Check if the application that we are waiting for is still focused.
939 std::shared_ptr<InputApplicationHandle> focusedApplication =
940 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
941 if (focusedApplication == nullptr ||
942 focusedApplication->getApplicationToken() !=
943 mAwaitedFocusedApplication->getApplicationToken()) {
944 // Unexpected because we should have reset the ANR timer when focused application changed
945 ALOGE("Waited for a focused window, but focused application has already changed to %s",
946 focusedApplication->getName().c_str());
947 return; // The focused application has changed.
948 }
949
chaviw98318de2021-05-19 16:45:23 -0500950 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500951 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
952 if (focusedWindowHandle != nullptr) {
953 return; // We now have a focused window. No need for ANR.
954 }
955 onAnrLocked(mAwaitedFocusedApplication);
956}
957
958/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 * Check if any of the connections' wait queues have events that are too old.
960 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
961 * Return the time at which we should wake up next.
962 */
963nsecs_t InputDispatcher::processAnrsLocked() {
964 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700965 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
967 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
968 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500969 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700970 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500971 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700972 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500974 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
976 }
977 }
978
979 // Check if any connection ANRs are due
980 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
981 if (currentTime < nextAnrCheck) { // most likely scenario
982 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
983 }
984
985 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700986 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700987 if (connection == nullptr) {
988 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
989 return nextAnrCheck;
990 }
991 connection->responsive = false;
992 // Stop waking up for this unresponsive connection
993 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000994 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700995 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996}
997
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800998std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700999 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001000 if (connection->monitor) {
1001 return mMonitorDispatchingTimeout;
1002 }
1003 const sp<WindowInfoHandle> window =
1004 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001005 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001006 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001007 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001008 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001009}
1010
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001011void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 nsecs_t currentTime = now();
1013
Jeff Browndc5992e2014-04-11 01:27:26 -07001014 // Reset the key repeat timer whenever normal dispatch is suspended while the
1015 // device is in a non-interactive state. This is to ensure that we abort a key
1016 // repeat if the device is just coming out of sleep.
1017 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 resetKeyRepeatLocked();
1019 }
1020
1021 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1022 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001023 if (DEBUG_FOCUS) {
1024 ALOGD("Dispatch frozen. Waiting some more.");
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 return;
1027 }
1028
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 // Ready to start a new event.
1030 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 // Synthesize a key repeat if appropriate.
1034 if (mKeyRepeatState.lastKeyEntry) {
1035 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1036 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1037 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001038 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040 }
1041
1042 // Nothing to do if there is no pending event.
1043 if (!mPendingEvent) {
1044 return;
1045 }
1046 } else {
1047 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 mPendingEvent = mInboundQueue.front();
1049 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 traceInboundQueueLengthLocked();
1051 }
1052
1053 // Poke user activity for this event.
1054 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001055 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058
1059 // Now we have an event to dispatch.
1060 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001065 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069
1070 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001071 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
1073
1074 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 const ConfigurationChangedEntry& typedEntry =
1077 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 break;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001083 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 const DeviceResetEntry& typedEntry =
1085 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 break;
1089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001091 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001092 std::shared_ptr<const FocusEntry> typedEntry =
1093 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001094 dispatchFocusLocked(currentTime, typedEntry);
1095 done = true;
1096 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1097 break;
1098 }
1099
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001100 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001101 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001102 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1103 done = true;
1104 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1105 break;
1106 }
1107
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1109 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001110 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001111 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1112 done = true;
1113 break;
1114 }
1115
arthurhungb89ccb02020-12-30 16:19:01 +08001116 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 std::shared_ptr<const DragEntry> typedEntry =
1118 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001119 dispatchDragLocked(currentTime, typedEntry);
1120 done = true;
1121 break;
1122 }
1123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001125 std::shared_ptr<const KeyEntry> keyEntry =
1126 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1131 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001133 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001134 if (done && mTracer) {
1135 ensureEventTraced(*keyEntry);
1136 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 break;
1139 }
1140
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001141 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001142 std::shared_ptr<const MotionEntry> motionEntry =
1143 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001144 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001145 // The event is stale. However, only drop stale events if there isn't an ongoing
1146 // gesture. That would allow us to complete the processing of the current stroke.
1147 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1148 if (touchStateIt != mTouchStatesByDisplay.end()) {
1149 const TouchState& touchState = touchStateIt->second;
1150 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1151 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1152 dropReason = DropReason::STALE;
1153 }
1154 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001157 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1158 // Only drop events that are focus-dispatched.
1159 dropReason = DropReason::BLOCKED;
1160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001163 if (done && mTracer) {
1164 ensureEventTraced(*motionEntry);
1165 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
Chris Yef59a2f42020-10-16 12:55:26 -07001169
1170 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001171 std::shared_ptr<const SensorEntry> sensorEntry =
1172 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001173
Chris Yef59a2f42020-10-16 12:55:26 -07001174 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1175 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1176 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1177 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1178 dropReason = DropReason::STALE;
1179 }
1180 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1181 done = true;
1182 break;
1183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
1185
1186 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
Michael Wright3a981722015-06-10 15:26:13 +01001190 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191
1192 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001193 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195}
1196
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001197bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001198 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001199}
1200
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201/**
1202 * Return true if the events preceding this incoming motion event should be dropped
1203 * Return false otherwise (the default behaviour)
1204 */
1205bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001207 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001208
1209 // Optimize case where the current application is unresponsive and the user
1210 // decides to touch a window in a different application.
1211 // If the application takes too long to catch up then we drop all events preceding
1212 // the touch into the other window.
1213 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001214 const int32_t displayId = motionEntry.displayId;
1215 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001216 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001217
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001218 sp<WindowInfoHandle> touchedWindowHandle =
1219 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001220 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001221 touchedWindowHandle->getApplicationToken() !=
1222 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001223 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 ALOGI("Pruning input queue because user touched a different application while waiting "
1225 "for %s",
1226 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001227 return true;
1228 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001229
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001230 // Alternatively, maybe there's a spy window that could handle this event.
1231 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1232 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1233 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001234 const std::shared_ptr<Connection> connection =
1235 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001236 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001237 // This spy window could take more input. Drop all events preceding this
1238 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001239 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001240 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001241 mAwaitedFocusedApplication->getName().c_str());
1242 return true;
1243 }
1244 }
1245 }
1246
1247 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1248 // yet been processed by some connections, the dispatcher will wait for these motion
1249 // events to be processed before dispatching the key event. This is because these motion events
1250 // may cause a new window to be launched, which the user might expect to receive focus.
1251 // To prevent waiting forever for such events, just send the key to the currently focused window
1252 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1253 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1254 "just send the pending key event to the focused window.");
1255 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001256 }
1257 return false;
1258}
1259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001261 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001263 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 traceInboundQueueLengthLocked();
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001267 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001268 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1269 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001272 if (mTracer) {
1273 ensureEventTraced(keyEntry);
1274 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001275
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001276 // If a new up event comes in, and the pending event with same key code has been asked
1277 // to try again later because of the policy. We have to reset the intercept key wake up
1278 // time for it may have been handled in the policy and could be dropped.
1279 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1280 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001281 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001282 if (pendingKey.keyCode == keyEntry.keyCode &&
1283 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001284 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1285 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001286 pendingKey.interceptKeyWakeupTime = 0;
1287 needWake = true;
1288 }
1289 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 break;
1291 }
1292
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001293 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001294 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1295 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001296 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1297 if (mTracer) {
1298 ensureEventTraced(motionEntry);
1299 }
1300 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001306 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001307 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1308 break;
1309 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001310 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001311 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001312 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001313 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001314 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1315 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001316 // nothing to do
1317 break;
1318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320
1321 return needWake;
1322}
1323
Prabir Pradhan24047542023-11-02 17:14:59 +00001324void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001325 // Do not store sensor event in recent queue to avoid flooding the queue.
1326 if (entry->type != EventEntry::Type::SENSOR) {
1327 mRecentQueue.push_back(entry);
1328 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001329 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001330 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
1332}
1333
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001334sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1335 bool isStylus,
1336 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001338 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001339 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001340 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001341 continue;
1342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001344 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001345 if (!info.isSpy() &&
1346 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001347 return windowHandle;
1348 }
1349 }
1350 return nullptr;
1351}
1352
1353std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001354 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001355 if (touchedWindow == nullptr) {
1356 return {};
1357 }
1358 // Traverse windows from front to back until we encounter the touched window.
1359 std::vector<InputTarget> outsideTargets;
1360 const auto& windowHandles = getWindowHandlesLocked(displayId);
1361 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1362 if (windowHandle == touchedWindow) {
1363 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1364 // below the touched window will not get ACTION_OUTSIDE event.
1365 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001366 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001367
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001369 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001370 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1371 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001372 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1373 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001374 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 }
1376 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001377 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378}
1379
Prabir Pradhand65552b2021-10-07 11:23:50 -07001380std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001381 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001382 // Traverse windows from front to back and gather the touched spy windows.
1383 std::vector<sp<WindowInfoHandle>> spyWindows;
1384 const auto& windowHandles = getWindowHandlesLocked(displayId);
1385 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1386 const WindowInfo& info = *windowHandle->getInfo();
1387
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001388 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001389 continue;
1390 }
1391 if (!info.isSpy()) {
1392 // The first touched non-spy window was found, so return the spy windows touched so far.
1393 return spyWindows;
1394 }
1395 spyWindows.push_back(windowHandle);
1396 }
1397 return spyWindows;
1398}
1399
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 const char* reason;
1402 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001403 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001404 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001405 ALOGD("Dropped event because policy consumed it.");
1406 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001407 reason = "inbound event was dropped because the policy consumed it";
1408 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001409 case DropReason::DISABLED:
1410 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 ALOGI("Dropped event because input dispatch is disabled.");
1412 }
1413 reason = "inbound event was dropped because input dispatch is disabled";
1414 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001415 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001416 LOG(INFO) << "Dropping because the current application is not responding and the user "
1417 "has started interacting with a different application: "
1418 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 reason = "inbound event was dropped because the current application is not responding "
1420 "and the user has started interacting with a different application";
1421 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001422 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 ALOGI("Dropped event because it is stale.");
1424 reason = "inbound event was dropped because it is stale";
1425 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001426 case DropReason::NO_POINTER_CAPTURE:
1427 ALOGI("Dropped event because there is no window with Pointer Capture.");
1428 reason = "inbound event was dropped because there is no window with Pointer Capture";
1429 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001430 case DropReason::NOT_DROPPED: {
1431 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001436 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001437 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001438 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001439 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1440 options.displayId = keyEntry.displayId;
1441 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001445 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1447 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001448 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001449 options.displayId = motionEntry.displayId;
1450 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 synthesizeCancelationEventsForAllConnectionsLocked(options);
1452 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001453 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1454 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001455 options.displayId = motionEntry.displayId;
1456 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 synthesizeCancelationEventsForAllConnectionsLocked(options);
1458 }
1459 break;
1460 }
Chris Yef59a2f42020-10-16 12:55:26 -07001461 case EventEntry::Type::SENSOR: {
1462 break;
1463 }
arthurhungb89ccb02020-12-30 16:19:01 +08001464 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1465 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 break;
1467 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001468 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001469 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001470 case EventEntry::Type::CONFIGURATION_CHANGED:
1471 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001472 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001473 break;
1474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 }
1476}
1477
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001479 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480}
1481
Prabir Pradhancef936d2021-07-21 16:17:52 +00001482bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001483 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 return false;
1485 }
1486
1487 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001488 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001489 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001490 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1491 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return true;
1494}
1495
Prabir Pradhancef936d2021-07-21 16:17:52 +00001496void InputDispatcher::postCommandLocked(Command&& command) {
1497 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498}
1499
1500void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001501 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001502 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001503 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 releaseInboundEventLocked(entry);
1505 }
1506 traceInboundQueueLengthLocked();
1507}
1508
1509void InputDispatcher::releasePendingEventLocked() {
1510 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 }
1514}
1515
Prabir Pradhan24047542023-11-02 17:14:59 +00001516void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001517 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001519 if (DEBUG_DISPATCH_CYCLE) {
1520 ALOGD("Injected inbound event was dropped.");
1521 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 }
1524 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001525 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528}
1529
1530void InputDispatcher::resetKeyRepeatLocked() {
1531 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001532 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534}
1535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001537 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
Michael Wright2e732952014-09-24 13:26:59 -07001539 uint32_t policyFlags = entry->policyFlags &
1540 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001543 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1544 currentTime, entry->deviceId, entry->source,
1545 entry->displayId, policyFlags, entry->action, entry->flags,
1546 entry->keyCode, entry->scanCode, entry->metaState,
1547 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001550 if (mTracer) {
1551 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1552 }
1553
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557}
1558
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001561 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1562 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564
1565 // Reset key repeating in case a keyboard device was added or removed or something.
1566 resetKeyRepeatLocked();
1567
1568 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001569 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1570 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001571 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001572 };
1573 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 return true;
1575}
1576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1578 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001579 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1580 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1581 entry.deviceId);
1582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583
liushenxiang42232912021-05-21 20:24:09 +08001584 // Reset key repeating in case a keyboard device was disabled or enabled.
1585 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1586 resetKeyRepeatLocked();
1587 }
1588
Michael Wrightfb04fd52022-11-24 22:31:11 +00001589 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001590 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001592
1593 // Remove all active pointers from this device
1594 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1595 touchState.removeAllPointersForDevice(entry.deviceId);
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 return true;
1598}
1599
Vishnu Nairad321cd2020-08-20 16:40:21 -07001600void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001601 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001602 if (mPendingEvent != nullptr) {
1603 // Move the pending event to the front of the queue. This will give the chance
1604 // for the pending event to get dispatched to the newly focused window
1605 mInboundQueue.push_front(mPendingEvent);
1606 mPendingEvent = nullptr;
1607 }
1608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001609 std::unique_ptr<FocusEntry> focusEntry =
1610 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1611 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001612
1613 // This event should go to the front of the queue, but behind all other focus events
1614 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001615 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1616 [](const std::shared_ptr<const EventEntry>& event) {
1617 return event->type == EventEntry::Type::FOCUS;
1618 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001619
1620 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001622}
1623
Prabir Pradhan24047542023-11-02 17:14:59 +00001624void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1625 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001626 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001627 if (channel == nullptr) {
1628 return; // Window has gone away
1629 }
1630 InputTarget target;
1631 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001632 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001633 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1634 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001635 std::string reason = std::string("reason=").append(entry->reason);
1636 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001637 dispatchEventLocked(currentTime, entry, {target});
1638}
1639
Prabir Pradhan99987712020-11-10 18:43:05 -08001640void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001641 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001642 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001643 dropReason = DropReason::NOT_DROPPED;
1644
Prabir Pradhan99987712020-11-10 18:43:05 -08001645 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001647
1648 if (entry->pointerCaptureRequest.enable) {
1649 // Enable Pointer Capture.
1650 if (haveWindowWithPointerCapture &&
1651 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001652 // This can happen if pointer capture is disabled and re-enabled before we notify the
1653 // app of the state change, so there is no need to notify the app.
1654 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1655 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001656 }
1657 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001658 // This can happen if a window requests capture and immediately releases capture.
1659 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001660 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001661 return;
1662 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001663 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1664 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1665 return;
1666 }
1667
Vishnu Nairc519ff72021-01-21 08:23:08 -08001668 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001669 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1670 mWindowTokenWithPointerCapture = token;
1671 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001672 // Disable Pointer Capture.
1673 // We do not check if the sequence number matches for requests to disable Pointer Capture
1674 // for two reasons:
1675 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1676 // to disable capture with the same sequence number: one generated by
1677 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1678 // Capture being disabled in InputReader.
1679 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1680 // actual Pointer Capture state that affects events being generated by input devices is
1681 // in InputReader.
1682 if (!haveWindowWithPointerCapture) {
1683 // Pointer capture was already forcefully disabled because of focus change.
1684 dropReason = DropReason::NOT_DROPPED;
1685 return;
1686 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001687 token = mWindowTokenWithPointerCapture;
1688 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001689 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001690 setPointerCaptureLocked(false);
1691 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001692 }
1693
1694 auto channel = getInputChannelLocked(token);
1695 if (channel == nullptr) {
1696 // Window has gone away, clean up Pointer Capture state.
1697 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001698 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001699 setPointerCaptureLocked(false);
1700 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001701 return;
1702 }
1703 InputTarget target;
1704 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001705 entry->dispatchInProgress = true;
1706 dispatchEventLocked(currentTime, entry, {target});
1707
1708 dropReason = DropReason::NOT_DROPPED;
1709}
1710
Prabir Pradhan24047542023-11-02 17:14:59 +00001711void InputDispatcher::dispatchTouchModeChangeLocked(
1712 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001713 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001714 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001715 if (windowHandles.empty()) {
1716 return;
1717 }
1718 const std::vector<InputTarget> inputTargets =
1719 getInputTargetsFromWindowHandlesLocked(windowHandles);
1720 if (inputTargets.empty()) {
1721 return;
1722 }
1723 entry->dispatchInProgress = true;
1724 dispatchEventLocked(currentTime, entry, inputTargets);
1725}
1726
1727std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1728 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1729 std::vector<InputTarget> inputTargets;
1730 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001731 const sp<IBinder>& token = handle->getToken();
1732 if (token == nullptr) {
1733 continue;
1734 }
1735 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1736 if (channel == nullptr) {
1737 continue; // Window has gone away
1738 }
1739 InputTarget target;
1740 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001741 inputTargets.push_back(target);
1742 }
1743 return inputTargets;
1744}
1745
Prabir Pradhan24047542023-11-02 17:14:59 +00001746bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001747 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 if (!entry->dispatchInProgress) {
1750 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1751 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1752 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1753 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001754 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 // We have seen two identical key downs in a row which indicates that the device
1756 // driver is automatically generating key repeats itself. We take note of the
1757 // repeat here, but we disable our own next key repeat timer since it is clear that
1758 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001759 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1760 // Make sure we don't get key down from a different device. If a different
1761 // device Id has same key pressed down, the new device Id will replace the
1762 // current one to hold the key repeat with repeat count reset.
1763 // In the future when got a KEY_UP on the device id, drop it and do not
1764 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1766 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001767 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 } else {
1769 // Not a repeat. Save key down state in case we do see a repeat later.
1770 resetKeyRepeatLocked();
1771 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1772 }
1773 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001774 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1775 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001776 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001777 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001778 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1779 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 resetKeyRepeatLocked();
1782 }
1783
1784 if (entry->repeatCount == 1) {
1785 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1786 } else {
1787 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1788 }
1789
1790 entry->dispatchInProgress = true;
1791
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001792 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794
1795 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001796 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001798 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return false; // wait until next wakeup
1800 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001801 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 entry->interceptKeyWakeupTime = 0;
1803 }
1804
1805 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001806 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001808 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001809 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001810
1811 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1812 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1813 };
1814 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001815 // Poke user activity for keys not passed to user
1816 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 return false; // wait for the command to run
1818 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001819 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001821 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001822 if (*dropReason == DropReason::NOT_DROPPED) {
1823 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825 }
1826
1827 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001828 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001829 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1831 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001832 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001833 // Poke user activity for undispatched keys
1834 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 return true;
1836 }
1837
1838 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001839 InputEventInjectionResult injectionResult;
1840 sp<WindowInfoHandle> focusedWindow =
1841 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1842 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 return false;
1845 }
1846
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001847 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 return true;
1850 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001851 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1852
1853 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001854 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1855 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001857 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001860 if (mTracer) {
1861 ensureEventTraced(*entry);
1862 for (const auto& target : inputTargets) {
1863 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1864 }
1865 }
1866
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 // Dispatch the key.
1868 dispatchEventLocked(currentTime, entry, inputTargets);
1869 return true;
1870}
1871
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001872void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001873 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1874 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1875 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1876 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1877 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1878 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1879 entry.metaState, entry.repeatCount, entry.downTime);
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881}
1882
Prabir Pradhancef936d2021-07-21 16:17:52 +00001883void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001884 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001885 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001886 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1887 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1888 "source=0x%x, sensorType=%s",
1889 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001890 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001891 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001892 auto command = [this, entry]() REQUIRES(mLock) {
1893 scoped_unlock unlock(mLock);
1894
1895 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001896 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001897 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001898 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1899 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001900 };
1901 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001902}
1903
1904bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001905 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1906 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001907 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001908 }
Chris Yef59a2f42020-10-16 12:55:26 -07001909 { // acquire lock
1910 std::scoped_lock _l(mLock);
1911
1912 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001913 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001914 if (entry->type == EventEntry::Type::SENSOR) {
1915 it = mInboundQueue.erase(it);
1916 releaseInboundEventLocked(entry);
1917 }
1918 }
1919 }
1920 return true;
1921}
1922
Prabir Pradhan24047542023-11-02 17:14:59 +00001923bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1924 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001925 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001926 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 entry->dispatchInProgress = true;
1930
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
1933
1934 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001935 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001936 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1938 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 return true;
1940 }
1941
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001942 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943
1944 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001945 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 if (isPointerEvent) {
1949 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001950
1951 if (mDragState &&
1952 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1953 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1954 pilferPointersLocked(mDragState->dragWindow->getToken());
1955 }
1956
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001957 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001958 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001959 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1960 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 } else {
1962 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001963 sp<WindowInfoHandle> focusedWindow =
1964 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1965 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1966 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001967 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1968 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1969 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 return false;
1974 }
1975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001976 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001977 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 return true;
1979 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001981 CancelationOptions::Mode mode(
1982 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1983 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001985 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 return true;
1988 }
1989
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001990 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001991 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001993 if (mTracer) {
1994 ensureEventTraced(*entry);
1995 for (const auto& target : inputTargets) {
1996 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1997 }
1998 }
1999
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 dispatchEventLocked(currentTime, entry, inputTargets);
2002 return true;
2003}
2004
chaviw98318de2021-05-19 16:45:23 -05002005void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002006 bool isExiting, const int32_t rawX,
2007 const int32_t rawY) {
2008 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002009 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002010 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2011 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002012
2013 enqueueInboundEventLocked(std::move(dragEntry));
2014}
2015
Prabir Pradhan24047542023-11-02 17:14:59 +00002016void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2017 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08002018 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
2019 if (channel == nullptr) {
2020 return; // Window has gone away
2021 }
2022 InputTarget target;
2023 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08002024 entry->dispatchInProgress = true;
2025 dispatchEventLocked(currentTime, entry, {target});
2026}
2027
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002028void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002029 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002030 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002031 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002032 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002033 "metaState=0x%x, buttonState=0x%x,"
2034 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002035 prefix, entry.eventTime, entry.deviceId,
2036 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2037 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2038 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2039 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002041 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002042 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002043 "x=%f, y=%f, pressure=%f, size=%f, "
2044 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2045 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002046 i, entry.pointerProperties[i].id,
2047 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002048 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2049 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2050 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2051 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2052 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2053 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2054 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2055 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2056 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059}
2060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002061void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002062 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002065 if (DEBUG_DISPATCH_CYCLE) {
2066 ALOGD("dispatchEventToCurrentInputTargets");
2067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002069 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002070
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2072
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002073 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002075 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002076 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002077 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002078 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002079 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002081 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2082 LOG(INFO) << "Dropping event delivery to target with channel "
2083 << inputTarget.inputChannel->getName()
2084 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086 }
2087 }
2088}
2089
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002090void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2092 // If the policy decides to close the app, we will get a channel removal event via
2093 // unregisterInputChannel, and will clean up the connection that way. We are already not
2094 // sending new pointers to the connection when it blocked, but focused events will continue to
2095 // pile up.
2096 ALOGW("Canceling events for %s because it is unresponsive",
2097 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002098 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002099 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002100 "application not responding");
2101 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
2103}
2104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002106 if (DEBUG_FOCUS) {
2107 ALOGD("Resetting ANR timeouts.");
2108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109
2110 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002112 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113}
2114
Tiger Huang721e26f2018-07-24 22:26:19 +08002115/**
2116 * Get the display id that the given event should go to. If this event specifies a valid display id,
2117 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2118 * Focused display is the display that the user most recently interacted with.
2119 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002120int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002121 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002122 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002123 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002124 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2125 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002126 break;
2127 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002128 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002129 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2130 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 break;
2132 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002133 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002134 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002135 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002136 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002137 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002138 case EventEntry::Type::SENSOR:
2139 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002140 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 return ADISPLAY_ID_NONE;
2142 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002143 }
2144 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2145}
2146
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002147bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2148 const char* focusedWindowName) {
2149 if (mAnrTracker.empty()) {
2150 // already processed all events that we waited for
2151 mKeyIsWaitingForEventsTimeout = std::nullopt;
2152 return false;
2153 }
2154
2155 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2156 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002157 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002158 mKeyIsWaitingForEventsTimeout = currentTime +
2159 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2160 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 return true;
2162 }
2163
2164 // We still have pending events, and already started the timer
2165 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2166 return true; // Still waiting
2167 }
2168
2169 // Waited too long, and some connection still hasn't processed all motions
2170 // Just send the key to the focused window
2171 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2172 focusedWindowName);
2173 mKeyIsWaitingForEventsTimeout = std::nullopt;
2174 return false;
2175}
2176
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002177sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002178 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002180 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181
Tiger Huang721e26f2018-07-24 22:26:19 +08002182 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002183 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002184 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002185 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2186
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 // If there is no currently focused window and no focused application
2188 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002189 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2190 ALOGI("Dropping %s event because there is no focused window or focused application in "
2191 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002192 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002193 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 }
2195
Vishnu Nair062a8672021-09-03 16:07:44 -07002196 // Drop key events if requested by input feature
2197 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002198 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002199 }
2200
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002201 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2202 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2203 // start interacting with another application via touch (app switch). This code can be removed
2204 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2205 // an app is expected to have a focused window.
2206 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2207 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2208 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002209 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2210 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2211 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002212 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002213 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002214 ALOGW("Waiting because no window has focus but %s may eventually add a "
2215 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002216 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002217 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002218 outInjectionResult = InputEventInjectionResult::PENDING;
2219 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002220 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2221 // Already raised ANR. Drop the event
2222 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002223 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002225 } else {
2226 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = InputEventInjectionResult::PENDING;
2228 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002229 }
2230 }
2231
2232 // we have a valid, non-null focused window
2233 resetNoFocusedWindowTimeoutLocked();
2234
Prabir Pradhan5735a322022-04-11 17:23:34 +00002235 // Verify targeted injection.
2236 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2237 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002238 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2239 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
2241
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002242 if (focusedWindowHandle->getInfo()->inputConfig.test(
2243 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002245 outInjectionResult = InputEventInjectionResult::PENDING;
2246 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 }
2248
2249 // If the event is a key event, then we must wait for all previous events to
2250 // complete before delivering it because previous events may have the
2251 // side-effect of transferring focus to a different window and we want to
2252 // ensure that the following keys are sent to the new window.
2253 //
2254 // Suppose the user touches a button in a window then immediately presses "A".
2255 // If the button causes a pop-up window to appear then we want to ensure that
2256 // the "A" key is delivered to the new pop-up window. This is because users
2257 // often anticipate pending UI changes when typing on a keyboard.
2258 // To obtain this behavior, we must serialize key events with respect to all
2259 // prior input events.
2260 if (entry.type == EventEntry::Type::KEY) {
2261 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002262 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002263 outInjectionResult = InputEventInjectionResult::PENDING;
2264 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002268 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2269 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270}
2271
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002272/**
2273 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2274 * that are currently unresponsive.
2275 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002276std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2277 const std::vector<Monitor>& monitors) const {
2278 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002279 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002280 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002281 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002282 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002283 if (connection == nullptr) {
2284 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002285 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002286 return false;
2287 }
2288 if (!connection->responsive) {
2289 ALOGW("Unresponsive monitor %s will not get the new gesture",
2290 connection->inputChannel->getName().c_str());
2291 return false;
2292 }
2293 return true;
2294 });
2295 return responsiveMonitors;
2296}
2297
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002298std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002299 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002300 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002301 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002303 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 // For security reasons, we defer updating the touch state until we are sure that
2305 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002306 const int32_t displayId = entry.displayId;
2307 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002308 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309
2310 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002311 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002313 // Copy current touch state into tempTouchState.
2314 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2315 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002316 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002317 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2319 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002320 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002321 }
2322
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002323 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002324
2325 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2326 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2327 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002328 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2329 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002330 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002331 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2332 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002333 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2334 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2335 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002336 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002337
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002338 if (newGesture) {
2339 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002340 }
2341
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002342 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2343 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2344 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 }
2346
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002347 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002348 if (wasDown) {
2349 // Started hovering, but the device is already down: reject the hover event
2350 LOG(ERROR) << "Got hover event " << entry.getDescription()
2351 << " but the device is already down " << oldState->dump();
2352 outInjectionResult = InputEventInjectionResult::FAILED;
2353 return {};
2354 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002355 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2356 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002357 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002358 }
2359
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2361 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002362 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002363 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002364 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002365 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2366 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002367 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002368 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002369 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002370
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002371 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002372 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002375 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002376 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002378 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002379 }
2380
Prabir Pradhan5735a322022-04-11 17:23:34 +00002381 // Verify targeted injection.
2382 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2383 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002384 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002385 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002386 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002387 }
2388
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002390 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2392 // New window supports splitting, but we should never split mouse events.
2393 isSplit = !isFromMouse;
2394 } else if (isSplit) {
2395 // New window does not support splitting but we have already split events.
2396 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002397 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2398 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002399 newTouchedWindowHandle = nullptr;
2400 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 } else {
2402 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002403 // be delivered to a new window which supports split touch. Pointers from a mouse device
2404 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002405 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002406 }
2407
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002408 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002409 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002411 // Process the foreground window first so that it is the first to receive the event.
2412 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413 }
2414
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002415 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002416 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2417 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002418 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002419 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002420 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002421 }
2422
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002424 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 continue;
2426 }
2427
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002428 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002429 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002430 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002431 }
2432
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002433 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002434 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002435
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002436 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2437 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002438 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002439 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002440
2441 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002442 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002443 }
2444 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002445 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002446 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002447 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002448 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002449
2450 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002451
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002452 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002453 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2454 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002455 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002456 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002457 isDownOrPointerDown
2458 ? std::make_optional(entry.eventTime)
2459 : std::nullopt);
2460 // If this is the pointer going down and the touched window has a wallpaper
2461 // then also add the touched wallpaper windows so they are locked in for the
2462 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2463 // SCROLL because the wallpaper engine only supports touch events. We would need to
2464 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2465 // handle these events.
2466 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002467 windowHandle->getInfo()->inputConfig.test(
2468 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2469 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2470 if (wallpaper != nullptr) {
2471 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2472 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002473 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002474 if (isSplit) {
2475 wallpaperFlags |= InputTarget::Flags::SPLIT;
2476 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002477 tempTouchState.addOrUpdateWindow(wallpaper,
2478 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002479 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002480 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002481 }
2482 }
2483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002485
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002486 // If a window is already pilfering some pointers, give it this new pointer as well and
2487 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2488 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002489 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002490 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002491 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002492 // This window is already pilfering some pointers, and this new pointer is also
2493 // going to it. Therefore, take over this pointer and don't give it to anyone
2494 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002495 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002496 }
2497 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002498
2499 // Restrict all pilfered pointers to the pilfering windows.
2500 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 } else {
2502 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2503
2504 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002505 if (!tempTouchState.isDown(entry.deviceId) &&
2506 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002507 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2508 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2509 << " is not down or we previously dropped the pointer down event in "
2510 << "display " << displayId << ": " << entry.getDescription();
2511 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002512 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002513 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 }
2515
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002516 // If the pointer is not currently hovering, then ignore the event.
2517 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2518 const int32_t pointerId = entry.pointerProperties[0].id;
2519 if (oldState == nullptr ||
2520 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2521 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2522 "display "
2523 << displayId << ": " << entry.getDescription();
2524 outInjectionResult = InputEventInjectionResult::FAILED;
2525 return {};
2526 }
2527 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2528 }
2529
arthurhung6d4bed92021-03-17 11:59:33 +08002530 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002531
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002533 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002534 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002535 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002536 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002537 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002538 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002539 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002540 sp<WindowInfoHandle> newTouchedWindowHandle =
2541 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002542
Prabir Pradhan5735a322022-04-11 17:23:34 +00002543 // Verify targeted injection.
2544 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2545 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002546 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002547 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002548 }
2549
Vishnu Nair062a8672021-09-03 16:07:44 -07002550 // Drop touch events if requested by input feature
2551 if (newTouchedWindowHandle != nullptr &&
2552 shouldDropInput(entry, newTouchedWindowHandle)) {
2553 newTouchedWindowHandle = nullptr;
2554 }
2555
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002556 if (newTouchedWindowHandle != nullptr &&
2557 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002558 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002559 oldTouchedWindowHandle->getName().c_str(),
2560 newTouchedWindowHandle->getName().c_str(), displayId);
2561
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002563 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002564 const PointerProperties& pointer = entry.pointerProperties[0];
2565 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002566
2567 const TouchedWindow& touchedWindow =
2568 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002569 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002570 InputTarget::DispatchMode::SLIPPERY_EXIT,
2571 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002572 touchedWindow.getDownTimeInTarget(entry.deviceId),
2573 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574
2575 // Make a slippery entrance into the new window.
2576 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002577 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
2579
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002580 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002581 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002582 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002585 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 }
2587 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002588 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002589 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002590 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
2592
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002593 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2594 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002595 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002596 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002597
2598 // Check if the wallpaper window should deliver the corresponding event.
2599 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002600 tempTouchState, entry.deviceId, pointer, targets);
2601 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002602 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604 }
Arthur Hung96483742022-11-15 03:30:48 +00002605
2606 // Update the pointerIds for non-splittable when it received pointer down.
2607 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2608 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002609 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002610 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2611 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002612 // Ignore drag window for it should just track one pointer.
2613 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2614 continue;
2615 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002616 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002617 }
2618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002621 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002622 {
2623 std::vector<TouchedWindow> hoveringWindows =
2624 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2625 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002626 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002627 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2628 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002629 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002630 if (!target) {
2631 continue;
2632 }
2633 // Hardcode to single hovering pointer for now.
2634 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2635 pointerIds.set(entry.pointerProperties[0].id);
2636 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2637 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640
Prabir Pradhan5735a322022-04-11 17:23:34 +00002641 // Ensure that all touched windows are valid for injection.
2642 if (entry.injectionState != nullptr) {
2643 std::string errs;
2644 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002645 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2646 if (err) errs += "\n - " + *err;
2647 }
2648 if (!errs.empty()) {
2649 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002650 "%s:%s",
2651 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002652 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002653 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002654 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002655 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002656
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002657 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2658 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002660 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002661 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002662 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002663 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002664 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002665 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002666 sp<WindowInfoHandle> targetWindow =
2667 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2668 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2669 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
2672 }
2673 }
2674 }
2675
Harry Cuttsb166c002023-05-09 13:06:05 +00002676 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2677 // only want the system UI to handle these gestures.
2678 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2679 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2680 if (isTouchpadNavGesture) {
2681 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2682 }
2683
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002684 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002685 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002686 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002687 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002688 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002689 continue;
2690 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002691 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002692 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002693 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002694 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002695
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002696 // During targeted injection, only allow owned targets to receive events
2697 std::erase_if(targets, [&](const InputTarget& target) {
2698 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2699 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2700 if (err) {
2701 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2702 << ": " << (*err);
2703 return true;
2704 }
2705 return false;
2706 });
2707
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002708 if (targets.empty()) {
2709 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2710 outInjectionResult = InputEventInjectionResult::FAILED;
2711 return {};
2712 }
2713
2714 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2715 // window that is actually receiving the entire gesture.
2716 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002717 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002718 })) {
2719 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2720 << entry.getDescription();
2721 outInjectionResult = InputEventInjectionResult::FAILED;
2722 return {};
2723 }
2724
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002725 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
Prabir Pradhan502a7252023-12-01 16:11:24 +00002727 // Now that we have generated all of the input targets for this event, reset the dispatch
2728 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002729 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002730 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 }
2732
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002733 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002734 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002735 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002736 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002737 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002738 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002739 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002740 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2741 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002742 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2743 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2744 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 }
2746
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002747 // Save changes unless the action was scroll in which case the temporary touch
2748 // state was only valid for this one action.
2749 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002750 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002751 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002752 mTouchStatesByDisplay[displayId] = tempTouchState;
2753 } else {
2754 mTouchStatesByDisplay.erase(displayId);
2755 }
2756 }
2757
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002758 if (tempTouchState.windows.empty()) {
2759 mTouchStatesByDisplay.erase(displayId);
2760 }
2761
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002762 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763}
2764
arthurhung6d4bed92021-03-17 11:59:33 +08002765void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002766 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2767 // have an explicit reason to support it.
2768 constexpr bool isStylus = false;
2769
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002770 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002771 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002772 if (dropWindow) {
2773 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002774 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002775 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002776 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002777 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002778 }
2779 mDragState.reset();
2780}
2781
2782void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002783 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002784 return;
2785 }
2786
arthurhung6d4bed92021-03-17 11:59:33 +08002787 if (!mDragState->isStartDrag) {
2788 mDragState->isStartDrag = true;
2789 mDragState->isStylusButtonDownAtStart =
2790 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2791 }
2792
Arthur Hung54745652022-04-20 07:17:41 +00002793 // Find the pointer index by id.
2794 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002795 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002796 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2797 if (pointerProperties.id == mDragState->pointerId) {
2798 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002799 }
Arthur Hung54745652022-04-20 07:17:41 +00002800 }
arthurhung6d4bed92021-03-17 11:59:33 +08002801
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002802 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002803 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002804 }
2805
2806 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2807 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2808 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2809
2810 switch (maskedAction) {
2811 case AMOTION_EVENT_ACTION_MOVE: {
2812 // Handle the special case : stylus button no longer pressed.
2813 bool isStylusButtonDown =
2814 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2815 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2816 finishDragAndDrop(entry.displayId, x, y);
2817 return;
2818 }
2819
2820 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2821 // until we have an explicit reason to support it.
2822 constexpr bool isStylus = false;
2823
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002824 sp<WindowInfoHandle> hoverWindowHandle =
2825 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2826 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002827 // enqueue drag exit if needed.
2828 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2829 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2830 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002831 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002832 y);
2833 }
2834 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2835 }
2836 // enqueue drag location if needed.
2837 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002838 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002839 }
2840 break;
2841 }
2842
2843 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002844 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002845 break;
2846 }
2847 // The drag pointer is up.
2848 [[fallthrough]];
2849 case AMOTION_EVENT_ACTION_UP:
2850 finishDragAndDrop(entry.displayId, x, y);
2851 break;
2852 case AMOTION_EVENT_ACTION_CANCEL: {
2853 ALOGD("Receiving cancel when drag and drop.");
2854 sendDropWindowCommandLocked(nullptr, 0, 0);
2855 mDragState.reset();
2856 break;
2857 }
arthurhungb89ccb02020-12-30 16:19:01 +08002858 }
2859}
2860
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002861std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2862 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002863 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002864 std::optional<nsecs_t> firstDownTimeInTarget) const {
2865 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2866 if (inputChannel == nullptr) {
2867 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2868 return {};
2869 }
2870 InputTarget inputTarget;
2871 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002872 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002873 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002874 inputTarget.flags = targetFlags;
2875 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2876 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2877 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2878 if (displayInfoIt != mDisplayInfos.end()) {
2879 inputTarget.displayTransform = displayInfoIt->second.transform;
2880 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002881 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002882 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2883 }
2884 return inputTarget;
2885}
2886
chaviw98318de2021-05-19 16:45:23 -05002887void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002888 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002889 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002890 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002891 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002892 std::vector<InputTarget>::iterator it =
2893 std::find_if(inputTargets.begin(), inputTargets.end(),
2894 [&windowHandle](const InputTarget& inputTarget) {
2895 return inputTarget.inputChannel->getConnectionToken() ==
2896 windowHandle->getToken();
2897 });
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) {
2936 return inputTarget.inputChannel->getConnectionToken() ==
2937 windowHandle->getToken();
2938 });
2939
2940 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2941 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2942 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2943 // input targets for hovering pointers and for touching pointers.
2944 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2945 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002946 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002947 // Force the code below to create a new input target
2948 it = inputTargets.end();
2949 }
2950
2951 const WindowInfo* windowInfo = windowHandle->getInfo();
2952
2953 if (it == inputTargets.end()) {
2954 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002955 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2956 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002957 if (!target) {
2958 return;
2959 }
2960 inputTargets.push_back(*target);
2961 it = inputTargets.end() - 1;
2962 }
2963
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002964 if (it->dispatchMode != dispatchMode) {
2965 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2966 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2967 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002968 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002969 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2970 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002971 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002972 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002973 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002974 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2975 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002976
chaviw1ff3d1e2020-07-01 15:53:47 -07002977 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978}
2979
Michael Wright3dd60e22019-03-27 22:06:44 +00002980void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002981 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002982 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2983 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002984
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002985 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2986 InputTarget target;
2987 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002988 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2989 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002990 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2991 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002992 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002993 target.setDefaultPointerTransform(target.displayTransform);
2994 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 }
2996}
2997
Robert Carrc9bf1d32020-04-13 17:21:08 -07002998/**
2999 * Indicate whether one window handle should be considered as obscuring
3000 * another window handle. We only check a few preconditions. Actually
3001 * checking the bounds is left to the caller.
3002 */
chaviw98318de2021-05-19 16:45:23 -05003003static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3004 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003005 // Compare by token so cloned layers aren't counted
3006 if (haveSameToken(windowHandle, otherHandle)) {
3007 return false;
3008 }
3009 auto info = windowHandle->getInfo();
3010 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003011 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003012 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003013 } else if (otherInfo->alpha == 0 &&
3014 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003015 // Those act as if they were invisible, so we don't need to flag them.
3016 // We do want to potentially flag touchable windows even if they have 0
3017 // opacity, since they can consume touches and alter the effects of the
3018 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003019 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003020 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3021 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003022 } else if (info->ownerUid == otherInfo->ownerUid) {
3023 // If ownerUid is the same we don't generate occlusion events as there
3024 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003025 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003026 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003027 return false;
3028 } else if (otherInfo->displayId != info->displayId) {
3029 return false;
3030 }
3031 return true;
3032}
3033
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003034/**
3035 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3036 * untrusted, one should check:
3037 *
3038 * 1. If result.hasBlockingOcclusion is true.
3039 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3040 * BLOCK_UNTRUSTED.
3041 *
3042 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3043 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3044 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3045 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3046 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3047 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3048 *
3049 * If neither of those is true, then it means the touch can be allowed.
3050 */
3051InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003052 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3053 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003054 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003055 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003056 TouchOcclusionInfo info;
3057 info.hasBlockingOcclusion = false;
3058 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003059 info.obscuringUid = gui::Uid::INVALID;
3060 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003061 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 if (windowHandle == otherHandle) {
3063 break; // All future windows are below us. Exit early.
3064 }
chaviw98318de2021-05-19 16:45:23 -05003065 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003066 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3067 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003068 if (DEBUG_TOUCH_OCCLUSION) {
3069 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003070 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003071 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003072 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3073 // we perform the checks below to see if the touch can be propagated or not based on the
3074 // window's touch occlusion mode
3075 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3076 info.hasBlockingOcclusion = true;
3077 info.obscuringUid = otherInfo->ownerUid;
3078 info.obscuringPackage = otherInfo->packageName;
3079 break;
3080 }
3081 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003082 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003083 float opacity =
3084 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3085 // Given windows A and B:
3086 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3087 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3088 opacityByUid[uid] = opacity;
3089 if (opacity > info.obscuringOpacity) {
3090 info.obscuringOpacity = opacity;
3091 info.obscuringUid = uid;
3092 info.obscuringPackage = otherInfo->packageName;
3093 }
3094 }
3095 }
3096 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003097 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003098 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003099 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003100 return info;
3101}
3102
chaviw98318de2021-05-19 16:45:23 -05003103std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003104 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003105 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003106 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3107 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3108 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003109 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003110 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003111 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3112 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003113 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3114 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3115 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003116 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003117}
3118
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003119bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3120 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003121 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3122 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003123 return false;
3124 }
3125 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003126 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003127 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003128 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003129 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3130 return false;
3131 }
3132 return true;
3133}
3134
chaviw98318de2021-05-19 16:45:23 -05003135bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003138 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3139 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003140 if (windowHandle == otherHandle) {
3141 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
chaviw98318de2021-05-19 16:45:23 -05003143 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003144 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003145 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 return true;
3147 }
3148 }
3149 return false;
3150}
3151
chaviw98318de2021-05-19 16:45:23 -05003152bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003153 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003154 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3155 const WindowInfo* windowInfo = windowHandle->getInfo();
3156 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003157 if (windowHandle == otherHandle) {
3158 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003159 }
chaviw98318de2021-05-19 16:45:23 -05003160 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003161 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003162 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003163 return true;
3164 }
3165 }
3166 return false;
3167}
3168
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003169std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003170 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003171 if (applicationHandle != nullptr) {
3172 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003173 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 } else {
3175 return applicationHandle->getName();
3176 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003177 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003178 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182}
3183
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003184void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003185 if (!isUserActivityEvent(eventEntry)) {
3186 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 return;
3188 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003189
3190 const int32_t eventType = getUserActivityEventType(eventEntry);
3191 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3192 // Note that we're directly getting the time diff between the current event and the previous
3193 // event. This is assuming that the first user event always happens at a timestamp that is
3194 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3195 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3196 // value than the potential first user activity event time, so this is ok.
3197 std::chrono::nanoseconds timeSinceLastEvent =
3198 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3199 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3200 return;
3201 }
3202 }
3203
Tiger Huang721e26f2018-07-24 22:26:19 +08003204 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003205 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003206 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003207 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003208 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003209 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003210 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 }
3212 }
3213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003215 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3217 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 return;
3219 }
Josep del Riob3981622023-04-18 15:49:45 +00003220 if (windowDisablingUserActivityInfo != nullptr) {
3221 if (DEBUG_DISPATCH_CYCLE) {
3222 ALOGD("Not poking user activity: disabled by window '%s'.",
3223 windowDisablingUserActivityInfo->name.c_str());
3224 }
3225 return;
3226 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003227 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003229 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003230 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3231 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 return;
3233 }
Josep del Riob3981622023-04-18 15:49:45 +00003234 // If the key code is unknown, we don't consider it user activity
3235 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3236 return;
3237 }
3238 // Don't inhibit events that were intercepted or are not passed to
3239 // the apps, like system shortcuts
3240 if (windowDisablingUserActivityInfo != nullptr &&
3241 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3242 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3243 if (DEBUG_DISPATCH_CYCLE) {
3244 ALOGD("Not poking user activity: disabled by window '%s'.",
3245 windowDisablingUserActivityInfo->name.c_str());
3246 }
3247 return;
3248 }
3249
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003252 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003253 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003254 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003255 break;
3256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
3258
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003259 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003260 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3261 REQUIRES(mLock) {
3262 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003263 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003264 };
3265 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266}
3267
3268void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003269 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003270 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003271 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003272 ATRACE_NAME_IF(ATRACE_ENABLED(),
3273 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3274 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003275 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003277 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003279 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003280 inputTarget.getPointerInfoString().c_str());
3281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
3283 // Skip this event if the connection status is not normal.
3284 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003285 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003286 if (DEBUG_DISPATCH_CYCLE) {
3287 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003288 connection->getInputChannelName().c_str(),
3289 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 return;
3292 }
3293
3294 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003296 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003298 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003300 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003301 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003302 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3303 logDispatchStateLocked();
3304 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3305 "target on connection "
3306 << connection->getInputChannelName() << " for "
3307 << originalMotionEntry.getDescription();
3308 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003309 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003310 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3311 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 if (!splitMotionEntry) {
3313 return; // split event was dropped
3314 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003315 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3316 std::string reason = std::string("reason=pointer cancel on split window");
3317 android_log_event_list(LOGTAG_INPUT_CANCEL)
3318 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3319 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003320 if (DEBUG_FOCUS) {
3321 ALOGD("channel '%s' ~ Split motion event.",
3322 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003323 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003324 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003325 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3326 std::move(splitMotionEntry),
3327 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 return;
3329 }
3330 }
3331
3332 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003333 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3334 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335}
3336
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003337void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3338 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3339 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003340 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003341 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3342 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003343 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003344
hongzuo liu95785e22022-09-06 02:51:35 +00003345 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003347 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
3349 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003350 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 startDispatchCycleLocked(currentTime, connection);
3352 }
3353}
3354
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003355void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003356 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003357 const InputTarget& inputTarget) {
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003358 // TODO(b/210460522): Verify all targets excluding global monitors are associated with a window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 // This is a new event.
3360 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003361 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003362 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003364 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3365 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003366 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003368 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003369 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003370 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3371 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003372 LOG(WARNING) << "channel " << connection->getInputChannelName()
3373 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 return; // skip the inconsistent event
3375 }
3376 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003379 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003380 std::shared_ptr<const MotionEntry> resolvedMotion =
3381 std::static_pointer_cast<const MotionEntry>(eventEntry);
3382 {
3383 // Determine the resolved motion entry.
3384 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3385 int32_t resolvedAction = motionEntry.action;
3386 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003388 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003389 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003390 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003391 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003392 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003393 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003394 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003395 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003396 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003397 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3398 }
3399 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3400 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3401 motionEntry.displayId)) {
3402 if (DEBUG_DISPATCH_CYCLE) {
3403 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3404 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3405 "enter event";
3406 }
3407 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3408 }
3409
3410 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3411 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3412 }
3413 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3414 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3415 }
3416 if (dispatchEntry->targetFlags.test(
3417 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3418 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3419 }
3420
3421 dispatchEntry->resolvedFlags = resolvedFlags;
3422 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003423 std::optional<std::vector<PointerProperties>> usingProperties;
3424 std::optional<std::vector<PointerCoords>> usingCoords;
3425 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3426 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3427 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3428 // the dispatcher, and therefore the coordinates of this event are currently
3429 // incorrect. These events should use the coordinates of the last dispatched
3430 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3431 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3432 std::optional<std::pair<std::vector<PointerProperties>,
3433 std::vector<PointerCoords>>>
3434 pointerInfo =
3435 connection->inputState.getPointersOfLastEvent(motionEntry,
3436 hovering);
3437 if (pointerInfo) {
3438 usingProperties = pointerInfo->first;
3439 usingCoords = pointerInfo->second;
3440 }
3441 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003442 // Generate a new MotionEntry with a new eventId using the resolved action and
3443 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003444 resolvedMotion = std::make_shared<
3445 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3446 motionEntry.eventTime, motionEntry.deviceId,
3447 motionEntry.source, motionEntry.displayId,
3448 motionEntry.policyFlags, resolvedAction,
3449 motionEntry.actionButton, resolvedFlags,
3450 motionEntry.metaState, motionEntry.buttonState,
3451 motionEntry.classification, motionEntry.edgeFlags,
3452 motionEntry.xPrecision, motionEntry.yPrecision,
3453 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3454 motionEntry.downTime,
3455 usingProperties.value_or(motionEntry.pointerProperties),
3456 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003457 if (ATRACE_ENABLED()) {
3458 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3459 ") to MotionEvent(id=0x%" PRIx32 ").",
3460 motionEntry.id, resolvedMotion->id);
3461 ATRACE_NAME(message.c_str());
3462 }
3463
3464 // Set the resolved motion entry in the DispatchEntry.
3465 dispatchEntry->eventEntry = resolvedMotion;
3466 eventEntry = resolvedMotion;
3467 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003470 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3471 // devices being active at the same time in the same window, so if a new device is
3472 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003473 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003474 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003475 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003476 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003477 << connection->getInputChannelName() << " with event "
3478 << cancelEvent->getDescription();
3479 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3480 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003481 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003482
3483 // Send these cancel events to the queue before sending the event from the new
3484 // device.
3485 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3486 }
3487
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003488 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003489 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003490 LOG(WARNING) << "channel " << connection->getInputChannelName()
3491 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003492 return; // skip the inconsistent event
3493 }
3494
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003495 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3496 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003497 // Skip reporting pointer down outside focus to the policy.
3498 break;
3499 }
3500
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003501 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003502 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003503
3504 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003506 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003507 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003508 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3509 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003510 break;
3511 }
Chris Yef59a2f42020-10-16 12:55:26 -07003512 case EventEntry::Type::SENSOR: {
3513 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3514 break;
3515 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003516 case EventEntry::Type::CONFIGURATION_CHANGED:
3517 case EventEntry::Type::DEVICE_RESET: {
3518 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003519 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003520 break;
3521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523
3524 // Remember that we are waiting for this dispatch to complete.
3525 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003526 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
3529 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003530 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003531 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003532}
3533
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003534/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003535 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003536 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003537 * The first role is to log input interaction with windows, which helps determine what the user was
3538 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3539 * that user started interacting with launcher window, as well as any other window that received
3540 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3541 * when the set of tokens that received the event changes. It is not logged again as long as the
3542 * user is interacting with the same windows.
3543 *
3544 * The second role is to track input device activity for metrics collection. For each input event,
3545 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3546 * input_interaction logs, the device interaction is reported even when the set of interaction
3547 * tokens do not change.
3548 *
3549 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3550 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003552void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3553 const std::vector<InputTarget>& targets) {
3554 int32_t deviceId;
3555 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003556 // Skip ACTION_UP events, and all events other than keys and motions
3557 if (entry.type == EventEntry::Type::KEY) {
3558 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3559 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3560 return;
3561 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003562 deviceId = keyEntry.deviceId;
3563 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003564 } else if (entry.type == EventEntry::Type::MOTION) {
3565 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3566 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003567 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3568 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003569 return;
3570 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003571 deviceId = motionEntry.deviceId;
3572 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003573 } else {
3574 return; // Not a key or a motion
3575 }
3576
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003577 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003578 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003579 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003580 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003581 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003582 continue; // Skip windows that receive ACTION_OUTSIDE
3583 }
3584
3585 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003586 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003587 if (connection == nullptr) {
3588 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003589 }
3590 newConnectionTokens.insert(std::move(token));
3591 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003592 if (target.windowHandle) {
3593 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3594 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003595 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003596
3597 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3598 REQUIRES(mLock) {
3599 scoped_unlock unlock(mLock);
3600 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3601 };
3602 postCommandLocked(std::move(command));
3603
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003604 if (newConnectionTokens == mInteractionConnectionTokens) {
3605 return; // no change
3606 }
3607 mInteractionConnectionTokens = newConnectionTokens;
3608
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003609 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003610 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003611 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003612 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003613 std::string message = "Interaction with: " + targetList;
3614 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003615 message += "<none>";
3616 }
3617 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3618}
3619
chaviwfd6d3512019-03-25 13:23:49 -07003620void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003621 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003622 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003623 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3624 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003625 return;
3626 }
3627
Vishnu Nairc519ff72021-01-21 08:23:08 -08003628 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003629 if (focusedToken == token) {
3630 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003631 return;
3632 }
3633
Prabir Pradhancef936d2021-07-21 16:17:52 +00003634 auto command = [this, token]() REQUIRES(mLock) {
3635 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003636 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003637 };
3638 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639}
3640
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003641status_t InputDispatcher::publishMotionEvent(Connection& connection,
3642 DispatchEntry& dispatchEntry) const {
3643 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3644 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3645
3646 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003647 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003648
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003649 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003650 // Set the X and Y offset and X and Y scale depending on the input source.
3651 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003652 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003653 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3654 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003655 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003656 scaledCoords[i] = motionEntry.pointerCoords[i];
3657 // Don't apply window scale here since we don't want scale to affect raw
3658 // coordinates. The scale will be sent back to the client and applied
3659 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003660 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003661 }
3662 usingCoords = scaledCoords;
3663 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003664 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003666 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003667 scaledCoords[i].clear();
3668 }
3669 usingCoords = scaledCoords;
3670 }
3671
3672 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3673
3674 // Publish the motion event.
3675 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003676 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3677 motionEntry.source, motionEntry.displayId, std::move(hmac),
3678 motionEntry.action, motionEntry.actionButton,
3679 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3680 motionEntry.metaState, motionEntry.buttonState,
3681 motionEntry.classification, dispatchEntry.transform,
3682 motionEntry.xPrecision, motionEntry.yPrecision,
3683 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3684 dispatchEntry.rawTransform, motionEntry.downTime,
3685 motionEntry.eventTime, motionEntry.getPointerCount(),
3686 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003687}
3688
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003690 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003691 ATRACE_NAME_IF(ATRACE_ENABLED(),
3692 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3693 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003694 if (DEBUG_DISPATCH_CYCLE) {
3695 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003698 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003699 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003701 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003702 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703
3704 // Publish the event.
3705 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003706 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3707 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003708 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003709 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3710 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003711 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003712 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3713 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003716 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003717 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003718 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3719 keyEntry.deviceId, keyEntry.source,
3720 keyEntry.displayId, std::move(hmac),
3721 keyEntry.action, dispatchEntry->resolvedFlags,
3722 keyEntry.keyCode, keyEntry.scanCode,
3723 keyEntry.metaState, keyEntry.repeatCount,
3724 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003725 if (mTracer) {
3726 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3727 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003728 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003731 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003732 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003733 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3734 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003735 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003736 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003737 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003738 if (mTracer) {
3739 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3740 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 break;
3742 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003743
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003744 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003745 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003746 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003748 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003749 break;
3750 }
3751
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003752 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3753 const TouchModeEntry& touchModeEntry =
3754 static_cast<const TouchModeEntry&>(eventEntry);
3755 status = connection->inputPublisher
3756 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3757 touchModeEntry.inTouchMode);
3758
3759 break;
3760 }
3761
Prabir Pradhan99987712020-11-10 18:43:05 -08003762 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3763 const auto& captureEntry =
3764 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3765 status = connection->inputPublisher
3766 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003767 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003768 break;
3769 }
3770
arthurhungb89ccb02020-12-30 16:19:01 +08003771 case EventEntry::Type::DRAG: {
3772 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3773 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3774 dragEntry.id, dragEntry.x,
3775 dragEntry.y,
3776 dragEntry.isExiting);
3777 break;
3778 }
3779
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003780 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003781 case EventEntry::Type::DEVICE_RESET:
3782 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003783 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003784 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 }
3788
3789 // Check the result.
3790 if (status) {
3791 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003792 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003794 "This is unexpected because the wait queue is empty, so the pipe "
3795 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003796 "event to it, status=%s(%d)",
3797 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3798 status);
Harry Cutts33476232023-01-30 19:57:29 +00003799 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 } else {
3801 // Pipe is full and we are waiting for the app to finish process some events
3802 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003803 if (DEBUG_DISPATCH_CYCLE) {
3804 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3805 "waiting for the application to catch up",
3806 connection->getInputChannelName().c_str());
3807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
3809 } else {
3810 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003811 "status=%s(%d)",
3812 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3813 status);
Harry Cutts33476232023-01-30 19:57:29 +00003814 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 return;
3817 }
3818
3819 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003820 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3821 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3822 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003823 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003825 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003826 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003827 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829}
3830
chaviw09c8d2d2020-08-24 15:48:26 -07003831std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3832 size_t size;
3833 switch (event.type) {
3834 case VerifiedInputEvent::Type::KEY: {
3835 size = sizeof(VerifiedKeyEvent);
3836 break;
3837 }
3838 case VerifiedInputEvent::Type::MOTION: {
3839 size = sizeof(VerifiedMotionEvent);
3840 break;
3841 }
3842 }
3843 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3844 return mHmacKeyManager.sign(start, size);
3845}
3846
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003847const std::array<uint8_t, 32> InputDispatcher::getSignature(
3848 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003849 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003850 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003851 // Only sign events up and down events as the purely move events
3852 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003853 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003854 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003855
3856 VerifiedMotionEvent verifiedEvent =
3857 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3858 verifiedEvent.actionMasked = actionMasked;
3859 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3860 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003861}
3862
3863const std::array<uint8_t, 32> InputDispatcher::getSignature(
3864 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3865 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3866 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003867 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003868}
3869
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003871 const std::shared_ptr<Connection>& connection,
3872 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003873 if (DEBUG_DISPATCH_CYCLE) {
3874 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3875 connection->getInputChannelName().c_str(), seq, toString(handled));
3876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003878 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 return;
3880 }
3881
3882 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003883 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3884 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3885 };
3886 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887}
3888
3889void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003890 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003891 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003892 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003893 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3894 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
3897 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003898 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003899 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003900 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003901 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
3903 // The connection appears to be unrecoverably broken.
3904 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003905 if (connection->status == Connection::Status::NORMAL) {
3906 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907
3908 if (notify) {
3909 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003910 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3911 connection->getInputChannelName().c_str());
3912
3913 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003914 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003915 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003916 };
3917 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 }
3919 }
3920}
3921
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003922void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003923 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003924 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003925 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 }
3927}
3928
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003929void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003931 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933}
3934
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003935int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3936 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003937 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003938 if (connection == nullptr) {
3939 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3940 connectionToken.get(), events);
3941 return 0; // remove the callback
3942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003944 bool notify;
3945 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3946 if (!(events & ALOOPER_EVENT_INPUT)) {
3947 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3948 "events=0x%x",
3949 connection->getInputChannelName().c_str(), events);
3950 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 }
3952
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003953 nsecs_t currentTime = now();
3954 bool gotOne = false;
3955 status_t status = OK;
3956 for (;;) {
3957 Result<InputPublisher::ConsumerResponse> result =
3958 connection->inputPublisher.receiveConsumerResponse();
3959 if (!result.ok()) {
3960 status = result.error().code();
3961 break;
3962 }
3963
3964 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3965 const InputPublisher::Finished& finish =
3966 std::get<InputPublisher::Finished>(*result);
3967 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3968 finish.consumeTime);
3969 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003970 if (shouldReportMetricsForConnection(*connection)) {
3971 const InputPublisher::Timeline& timeline =
3972 std::get<InputPublisher::Timeline>(*result);
3973 mLatencyTracker
3974 .trackGraphicsLatency(timeline.inputEventId,
3975 connection->inputChannel->getConnectionToken(),
3976 std::move(timeline.graphicsTimeline));
3977 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003978 }
3979 gotOne = true;
3980 }
3981 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003982 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003983 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 return 1;
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003988 notify = status != DEAD_OBJECT || !connection->monitor;
3989 if (notify) {
3990 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3991 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3992 status);
3993 }
3994 } else {
3995 // Monitor channels are never explicitly unregistered.
3996 // We do it automatically when the remote endpoint is closed so don't warn about them.
3997 const bool stillHaveWindowHandle =
3998 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3999 notify = !connection->monitor && stillHaveWindowHandle;
4000 if (notify) {
4001 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4002 connection->getInputChannelName().c_str(), events);
4003 }
4004 }
4005
4006 // Remove the channel.
4007 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
4008 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009}
4010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004011void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004013 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00004014 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 }
4016}
4017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004019 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004020 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004021 for (const Monitor& monitor : monitors) {
4022 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004023 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004024 }
4025}
4026
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004028 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004029 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004030 if (connection == nullptr) {
4031 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004033
4034 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035}
4036
4037void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004038 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004039 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 return;
4041 }
4042
4043 nsecs_t currentTime = now();
4044
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004045 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004046 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004048 if (cancelationEvents.empty()) {
4049 return;
4050 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004051
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004052 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4053 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004054 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004055 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004056 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004057 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058
Arthur Hungb3307ee2021-10-14 10:57:37 +00004059 std::string reason = std::string("reason=").append(options.reason);
4060 android_log_event_list(LOGTAG_INPUT_CANCEL)
4061 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4062
hongzuo liu95785e22022-09-06 02:51:35 +00004063 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004064 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004065 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004066 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004067
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004068 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004070 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004071
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004072 switch (cancelationEventEntry->type) {
4073 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004074 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004075 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4076 ? std::make_optional(keyEntry.displayId)
4077 : std::nullopt;
4078 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004079 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4080 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004081 } else {
4082 targets.emplace_back(fallbackTarget);
4083 }
4084 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004085 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004087 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004088 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004089 const std::optional<int32_t> targetDisplay =
4090 motionEntry.displayId != ADISPLAY_ID_NONE
4091 ? std::make_optional(motionEntry.displayId)
4092 : std::nullopt;
4093 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004094 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004095 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004096 pointerIndex++) {
4097 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4098 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004099 if (mDragState && mDragState->dragWindow->getToken() == token &&
4100 pointerIds.test(mDragState->pointerId)) {
4101 LOG(INFO) << __func__
4102 << ": Canceling drag and drop because the pointers for the drag "
4103 "window are being canceled.";
4104 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4105 mDragState.reset();
4106 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004107 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4108 ftl::Flags<InputTarget::Flags>(), pointerIds,
4109 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004110 } else {
4111 targets.emplace_back(fallbackTarget);
4112 const auto it = mDisplayInfos.find(motionEntry.displayId);
4113 if (it != mDisplayInfos.end()) {
4114 targets.back().displayTransform = it->second.transform;
4115 targets.back().setDefaultPointerTransform(it->second.transform);
4116 }
4117 }
4118 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004119 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004121 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004122 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004123 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4124 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004125 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004126 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004127 break;
4128 }
4129 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004130 case EventEntry::Type::DEVICE_RESET:
4131 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004132 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004133 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004134 break;
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 }
4137
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004138 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004139 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004141
hongzuo liu95785e22022-09-06 02:51:35 +00004142 // If the outbound queue was previously empty, start the dispatch cycle going.
4143 if (wasEmpty && !connection->outboundQueue.empty()) {
4144 startDispatchCycleLocked(currentTime, connection);
4145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146}
4147
Svet Ganov5d3bc372020-01-26 23:11:07 -08004148void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004149 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004150 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004151 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004152 return;
4153 }
4154
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004155 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004156 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004157
4158 if (downEvents.empty()) {
4159 return;
4160 }
4161
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004162 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004163 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4164 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004165 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004166
chaviw98318de2021-05-19 16:45:23 -05004167 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004168 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004169
hongzuo liu95785e22022-09-06 02:51:35 +00004170 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004171 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004172 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004173 switch (downEventEntry->type) {
4174 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004175 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4176 if (windowHandle != nullptr) {
4177 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004178 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004179 pointerIndex++) {
4180 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4181 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004182 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4183 targetFlags, pointerIds, motionEntry.downTime,
4184 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004185 } else {
4186 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4187 .flags = targetFlags});
4188 const auto it = mDisplayInfos.find(motionEntry.displayId);
4189 if (it != mDisplayInfos.end()) {
4190 targets.back().displayTransform = it->second.transform;
4191 targets.back().setDefaultPointerTransform(it->second.transform);
4192 }
4193 }
4194 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195 break;
4196 }
4197
4198 case EventEntry::Type::KEY:
4199 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004200 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004201 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004202 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004203 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004204 case EventEntry::Type::SENSOR:
4205 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004206 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004207 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004208 break;
4209 }
4210 }
4211
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004212 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004213 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004214 }
4215
hongzuo liu95785e22022-09-06 02:51:35 +00004216 // If the outbound queue was previously empty, start the dispatch cycle going.
4217 if (wasEmpty && !connection->outboundQueue.empty()) {
4218 startDispatchCycleLocked(downTime, connection);
4219 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004220}
4221
Arthur Hungc539dbb2022-12-08 07:45:36 +00004222void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4223 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4224 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004225 std::shared_ptr<Connection> wallpaperConnection =
4226 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004227 if (wallpaperConnection != nullptr) {
4228 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4229 }
4230 }
4231}
4232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004234 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4235 nsecs_t splitDownTime) {
4236 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
4238 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004239 std::vector<PointerProperties> splitPointerProperties;
4240 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004242 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 uint32_t splitPointerCount = 0;
4244
4245 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004248 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004250 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004252 splitPointerProperties.push_back(pointerProperties);
4253 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 splitPointerCount += 1;
4255 }
4256 }
4257
4258 if (splitPointerCount != pointerIds.count()) {
4259 // This is bad. We are missing some of the pointers that we expected to deliver.
4260 // Most likely this indicates that we received an ACTION_MOVE events that has
4261 // different pointer ids than we expected based on the previous ACTION_DOWN
4262 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4263 // in this way.
4264 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004265 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004266 "a broken sequence of pointer ids from the input device: %s",
4267 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004268 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004271 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4274 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004275 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004277 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004279 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 if (pointerIds.count() == 1) {
4281 // The first/last pointer went down/up.
4282 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004284 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4285 ? AMOTION_EVENT_ACTION_CANCEL
4286 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 } else {
4288 // A secondary pointer went down/up.
4289 uint32_t splitPointerIndex = 0;
4290 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4291 splitPointerIndex += 1;
4292 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 action = maskedAction |
4294 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
4296 } else {
4297 // An unrelated pointer changed.
4298 action = AMOTION_EVENT_ACTION_MOVE;
4299 }
4300 }
4301
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004302 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4303 logDispatchStateLocked();
4304 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4305 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4306 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004307 }
4308
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004309 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004310 ATRACE_NAME_IF(ATRACE_ENABLED(),
4311 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4312 ").",
4313 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004314 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004315 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4316 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004317 originalMotionEntry.deviceId, originalMotionEntry.source,
4318 originalMotionEntry.displayId,
4319 originalMotionEntry.policyFlags, action,
4320 originalMotionEntry.actionButton,
4321 originalMotionEntry.flags, originalMotionEntry.metaState,
4322 originalMotionEntry.buttonState,
4323 originalMotionEntry.classification,
4324 originalMotionEntry.edgeFlags,
4325 originalMotionEntry.xPrecision,
4326 originalMotionEntry.yPrecision,
4327 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004328 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004329 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 return splitMotionEntry;
4332}
4333
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004334void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4335 std::scoped_lock _l(mLock);
4336 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4337}
4338
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004339void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004340 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004341 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Antonio Kantekf16f2832021-09-28 04:39:20 +00004344 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004349 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 } // release lock
4352
4353 if (needWake) {
4354 mLooper->wake();
4355 }
4356}
4357
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004358void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004359 ALOGD_IF(debugInboundEventDetails(),
4360 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4361 ", deviceId=%d, source=%s, displayId=%" PRId32
4362 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4363 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004364 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4365 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4366 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004367 Result<void> keyCheck = validateKeyEvent(args.action);
4368 if (!keyCheck.ok()) {
4369 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 return;
4371 }
4372
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 uint32_t policyFlags = args.policyFlags;
4374 int32_t flags = args.flags;
4375 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004376 // InputDispatcher tracks and generates key repeats on behalf of
4377 // whatever notifies it, so repeatCount should always be set to 0
4378 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4380 policyFlags |= POLICY_FLAG_VIRTUAL;
4381 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 if (policyFlags & POLICY_FLAG_FUNCTION) {
4384 metaState |= AMETA_FUNCTION_ON;
4385 }
4386
4387 policyFlags |= POLICY_FLAG_TRUSTED;
4388
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004389 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4392 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4393 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394
Michael Wright2b3c3302018-03-02 17:19:13 +00004395 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004396 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004397 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4398 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
Antonio Kantekf16f2832021-09-28 04:39:20 +00004402 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 { // acquire lock
4404 mLock.lock();
4405
4406 if (shouldSendKeyToInputFilterLocked(args)) {
4407 mLock.unlock();
4408
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004409 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004410 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 return; // event was consumed by the filter
4412 }
4413
4414 mLock.lock();
4415 }
4416
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004417 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004418 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4419 args.deviceId, args.source, args.displayId, policyFlags,
4420 args.action, flags, keyCode, args.scanCode, metaState,
4421 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004422 if (mTracer) {
4423 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 mLock.unlock();
4428 } // release lock
4429
4430 if (needWake) {
4431 mLooper->wake();
4432 }
4433}
4434
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 return mInputFilterEnabled;
4437}
4438
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004439void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004440 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004441 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004442 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004443 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4445 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004446 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4447 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4448 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4449 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4450 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004451 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004452 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4453 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004454 i, args.pointerProperties[i].id,
4455 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4456 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4457 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4458 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4459 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4460 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4461 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4462 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4463 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4464 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004467
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004468 Result<void> motionCheck =
4469 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4470 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004471 if (!motionCheck.ok()) {
4472 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4473 return;
4474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004476 if (DEBUG_VERIFY_EVENTS) {
4477 auto [it, _] =
4478 mVerifiersByDisplay.try_emplace(args.displayId,
4479 StringPrintf("display %" PRId32, args.displayId));
4480 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004481 it->second.processMovement(args.deviceId, args.source, args.action,
4482 args.getPointerCount(), args.pointerProperties.data(),
4483 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004484 if (!result.ok()) {
4485 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4486 }
4487 }
4488
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004489 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004491
4492 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004493 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4494 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004495 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4496 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004497 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499
Antonio Kantekf16f2832021-09-28 04:39:20 +00004500 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 { // acquire lock
4502 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004503 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4504 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4505 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004506 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004507 if (touchStateIt != mTouchStatesByDisplay.end()) {
4508 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004509 if (touchState.hasTouchingPointers(args.deviceId) ||
4510 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004511 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4512 }
4513 }
4514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515
4516 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004517 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004518 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004519 displayTransform = it->second.transform;
4520 }
4521
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 mLock.unlock();
4523
4524 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004525 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4526 args.action, args.actionButton, args.flags, args.edgeFlags,
4527 args.metaState, args.buttonState, args.classification,
4528 displayTransform, args.xPrecision, args.yPrecision,
4529 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004530 args.downTime, args.eventTime, args.getPointerCount(),
4531 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532
4533 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004534 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 return; // event was consumed by the filter
4536 }
4537
4538 mLock.lock();
4539 }
4540
4541 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004542 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004543 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4544 args.deviceId, args.source, args.displayId,
4545 policyFlags, args.action, args.actionButton,
4546 args.flags, args.metaState, args.buttonState,
4547 args.classification, args.edgeFlags, args.xPrecision,
4548 args.yPrecision, args.xCursorPosition,
4549 args.yCursorPosition, args.downTime,
4550 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004551 if (mTracer) {
4552 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004555 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4556 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004557 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004558 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004559 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4560 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4561 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004562 }
4563
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004564 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 mLock.unlock();
4566 } // release lock
4567
4568 if (needWake) {
4569 mLooper->wake();
4570 }
4571}
4572
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004573void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004574 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004575 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4576 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004577 args.id, args.eventTime, args.deviceId, args.source,
4578 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004579 }
Chris Yef59a2f42020-10-16 12:55:26 -07004580
Antonio Kantekf16f2832021-09-28 04:39:20 +00004581 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004582 { // acquire lock
4583 mLock.lock();
4584
4585 // Just enqueue a new sensor event.
4586 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004587 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4588 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4589 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004590
4591 needWake = enqueueInboundEventLocked(std::move(newEntry));
4592 mLock.unlock();
4593 } // release lock
4594
4595 if (needWake) {
4596 mLooper->wake();
4597 }
4598}
4599
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004600void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004601 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004602 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4603 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004604 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004605 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004606}
4607
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004608bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004609 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610}
4611
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004612void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004613 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004614 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4615 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004616 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004619 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004621 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622}
4623
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004624void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004625 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004626 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4627 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629
Antonio Kantekf16f2832021-09-28 04:39:20 +00004630 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004632 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004634 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004635 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004636 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004637
4638 for (auto& [_, verifier] : mVerifiersByDisplay) {
4639 verifier.resetDevice(args.deviceId);
4640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 } // release lock
4642
4643 if (needWake) {
4644 mLooper->wake();
4645 }
4646}
4647
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004648void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004649 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004650 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4651 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004652 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004653
Antonio Kantekf16f2832021-09-28 04:39:20 +00004654 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004655 { // acquire lock
4656 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004657 auto entry =
4658 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004659 needWake = enqueueInboundEventLocked(std::move(entry));
4660 } // release lock
4661
4662 if (needWake) {
4663 mLooper->wake();
4664 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004665}
4666
Prabir Pradhan5735a322022-04-11 17:23:34 +00004667InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004668 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004669 InputEventInjectionSync syncMode,
4670 std::chrono::milliseconds timeout,
4671 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004672 Result<void> eventValidation = validateInputEvent(*event);
4673 if (!eventValidation.ok()) {
4674 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4675 return InputEventInjectionResult::FAILED;
4676 }
4677
Prabir Pradhan65613802023-02-22 23:36:58 +00004678 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004679 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4680 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4681 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4682 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004683 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004684 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Prabir Pradhan5735a322022-04-11 17:23:34 +00004686 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004688 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004689 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4690 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4691 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4692 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4693 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004694 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004695 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004696 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004697 }
4698
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004699 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4700 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4701
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004702 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004704 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004705 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004706 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004707 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004708 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4709 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4710 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004711 int32_t keyCode = incomingKey.getKeyCode();
4712 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004713 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004714 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004715 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4716 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4717 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004719 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4720 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004721 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722
4723 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4724 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004725 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004726 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4727 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4728 std::to_string(t.duration().count()).c_str());
4729 }
4730 }
4731
4732 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004733 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004734 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4735 incomingKey.getEventTime(), resolvedDeviceId,
4736 incomingKey.getSource(), incomingKey.getDisplayId(),
4737 policyFlags, action, flags, keyCode,
4738 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004739 incomingKey.getRepeatCount(),
4740 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004741 if (mTracer) {
4742 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4743 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004744 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 }
4747
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004748 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004749 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004750 const bool isPointerEvent =
4751 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4752 // If a pointer event has no displayId specified, inject it to the default display.
4753 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4754 ? ADISPLAY_ID_DEFAULT
4755 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004756 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757
4758 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004759 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004761 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4762 motionEvent.getAction(), eventTime,
4763 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4765 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4766 std::to_string(t.duration().count()).c_str());
4767 }
4768 }
4769
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004770 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4771 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4772 }
4773
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004774 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004775 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004776 const size_t pointerCount = motionEvent.getPointerCount();
4777 const std::vector<PointerProperties>
4778 pointerProperties(motionEvent.getPointerProperties(),
4779 motionEvent.getPointerProperties() + pointerCount);
4780
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004781 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004782 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004783 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4784 *sampleEventTimes, resolvedDeviceId,
4785 motionEvent.getSource(), displayId, policyFlags,
4786 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004787 motionEvent.getActionButton(), flags,
4788 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004789 motionEvent.getButtonState(),
4790 motionEvent.getClassification(),
4791 motionEvent.getEdgeFlags(),
4792 motionEvent.getXPrecision(),
4793 motionEvent.getYPrecision(),
4794 motionEvent.getRawXCursorPosition(),
4795 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004796 motionEvent.getDownTime(), pointerProperties,
4797 std::vector<PointerCoords>(samplePointerCoords,
4798 samplePointerCoords +
4799 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004800 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004801 if (mTracer) {
4802 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4803 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004804 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004805 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004806 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004807 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004808 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004809 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4810 resolvedDeviceId, motionEvent.getSource(), displayId,
4811 policyFlags, motionEvent.getAction(),
4812 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004813 motionEvent.getMetaState(), motionEvent.getButtonState(),
4814 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4815 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4816 motionEvent.getRawXCursorPosition(),
4817 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4818 pointerProperties,
4819 std::vector<PointerCoords>(samplePointerCoords,
4820 samplePointerCoords +
4821 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004822 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4823 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004824 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 }
4826 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004829 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004830 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004831 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 }
4833
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004835 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004836 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004837 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004838 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004839 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004840 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 }
4842
4843 mLock.unlock();
4844
4845 if (needWake) {
4846 mLooper->wake();
4847 }
4848
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004851 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004853 if (syncMode == InputEventInjectionSync::NONE) {
4854 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 } else {
4856 for (;;) {
4857 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004858 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 break;
4860 }
4861
4862 nsecs_t remainingTimeout = endTime - now();
4863 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004864 if (DEBUG_INJECTION) {
4865 ALOGD("injectInputEvent - Timed out waiting for injection result "
4866 "to become available.");
4867 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004868 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 break;
4870 }
4871
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004872 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4876 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004878 if (DEBUG_INJECTION) {
4879 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4880 injectionState->pendingForegroundDispatches);
4881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 nsecs_t remainingTimeout = endTime - now();
4883 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004884 if (DEBUG_INJECTION) {
4885 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4886 "dispatches to finish.");
4887 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004888 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 break;
4890 }
4891
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004892 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 }
4894 }
4895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 } // release lock
4897
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004898 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004899 LOG(INFO) << "injectInputEvent - Finished with result "
4900 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902
4903 return injectionResult;
4904}
4905
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004906std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004907 std::array<uint8_t, 32> calculatedHmac;
4908 std::unique_ptr<VerifiedInputEvent> result;
4909 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004910 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004911 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4912 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4913 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004914 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004915 break;
4916 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004917 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004918 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4919 VerifiedMotionEvent verifiedMotionEvent =
4920 verifiedMotionEventFromMotionEvent(motionEvent);
4921 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004922 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004923 break;
4924 }
4925 default: {
4926 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4927 return nullptr;
4928 }
4929 }
4930 if (calculatedHmac == INVALID_HMAC) {
4931 return nullptr;
4932 }
tyiu1573a672023-02-21 22:38:32 +00004933 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004934 return nullptr;
4935 }
4936 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004937}
4938
Prabir Pradhan24047542023-11-02 17:14:59 +00004939void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004940 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004941 if (!entry.injectionState) {
4942 // Not an injected event.
4943 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004945
4946 InjectionState& injectionState = *entry.injectionState;
4947 if (DEBUG_INJECTION) {
4948 LOG(INFO) << "Setting input event injection result to "
4949 << ftl::enum_string(injectionResult);
4950 }
4951
4952 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4953 // Log the outcome since the injector did not wait for the injection result.
4954 switch (injectionResult) {
4955 case InputEventInjectionResult::SUCCEEDED:
4956 ALOGV("Asynchronous input event injection succeeded.");
4957 break;
4958 case InputEventInjectionResult::TARGET_MISMATCH:
4959 ALOGV("Asynchronous input event injection target mismatch.");
4960 break;
4961 case InputEventInjectionResult::FAILED:
4962 ALOGW("Asynchronous input event injection failed.");
4963 break;
4964 case InputEventInjectionResult::TIMED_OUT:
4965 ALOGW("Asynchronous input event injection timed out.");
4966 break;
4967 case InputEventInjectionResult::PENDING:
4968 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4969 break;
4970 }
4971 }
4972
4973 injectionState.injectionResult = injectionResult;
4974 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975}
4976
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004977void InputDispatcher::transformMotionEntryForInjectionLocked(
4978 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004979 // Input injection works in the logical display coordinate space, but the input pipeline works
4980 // display space, so we need to transform the injected events accordingly.
4981 const auto it = mDisplayInfos.find(entry.displayId);
4982 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004983 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004984
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004985 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4986 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4987 const vec2 cursor =
4988 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4989 {entry.xCursorPosition, entry.yCursorPosition});
4990 entry.xCursorPosition = cursor.x;
4991 entry.yCursorPosition = cursor.y;
4992 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004993 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004994 entry.pointerCoords[i] =
4995 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4996 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004997 }
4998}
4999
Prabir Pradhan24047542023-11-02 17:14:59 +00005000void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005001 if (entry.injectionState) {
5002 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
5004}
5005
Prabir Pradhan24047542023-11-02 17:14:59 +00005006void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005007 if (entry.injectionState) {
5008 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005010 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005011 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012 }
5013 }
5014}
5015
chaviw98318de2021-05-19 16:45:23 -05005016const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005017 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005018 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005019 auto it = mWindowHandlesByDisplay.find(displayId);
5020 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005021}
5022
chaviw98318de2021-05-19 16:45:23 -05005023sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005024 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005025 if (windowHandleToken == nullptr) {
5026 return nullptr;
5027 }
5028
Prabir Pradhan16463382023-10-12 23:03:19 +00005029 if (!displayId) {
5030 // Look through all displays.
5031 for (auto& it : mWindowHandlesByDisplay) {
5032 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5033 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5034 if (windowHandle->getToken() == windowHandleToken) {
5035 return windowHandle;
5036 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005039 return nullptr;
5040 }
5041
Prabir Pradhan16463382023-10-12 23:03:19 +00005042 // Only look through the requested display.
5043 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005044 if (windowHandle->getToken() == windowHandleToken) {
5045 return windowHandle;
5046 }
5047 }
5048 return nullptr;
5049}
5050
chaviw98318de2021-05-19 16:45:23 -05005051sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5052 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005053 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005054 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5055 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005056 if (handle->getId() == windowHandle->getId() &&
5057 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005058 if (windowHandle->getInfo()->displayId != it.first) {
5059 ALOGE("Found window %s in display %" PRId32
5060 ", but it should belong to display %" PRId32,
5061 windowHandle->getName().c_str(), it.first,
5062 windowHandle->getInfo()->displayId);
5063 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005064 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 }
5067 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005068 return nullptr;
5069}
5070
chaviw98318de2021-05-19 16:45:23 -05005071sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005072 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5073 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074}
5075
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005076ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5077 auto displayInfoIt = mDisplayInfos.find(displayId);
5078 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5079 : kIdentityTransform;
5080}
5081
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005082bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5083 const MotionEntry& motionEntry) const {
5084 const WindowInfo& info = *window->getInfo();
5085
5086 // Skip spy window targets that are not valid for targeted injection.
5087 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005088 return false;
5089 }
5090
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005091 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5092 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5093 return false;
5094 }
5095
5096 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5097 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5098 window->getName().c_str());
5099 return false;
5100 }
5101
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005102 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005103 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005104 ALOGW("Not sending touch to %s because there's no corresponding connection",
5105 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005106 return false;
5107 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005108
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005109 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005110 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005111 return false;
5112 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005113
5114 // Drop events that can't be trusted due to occlusion
5115 const auto [x, y] = resolveTouchedPosition(motionEntry);
5116 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5117 if (!isTouchTrustedLocked(occlusionInfo)) {
5118 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005119 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005120 for (const auto& log : occlusionInfo.debugInfo) {
5121 ALOGD("%s", log.c_str());
5122 }
5123 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005124 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5125 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005126 return false;
5127 }
5128
5129 // Drop touch events if requested by input feature
5130 if (shouldDropInput(motionEntry, window)) {
5131 return false;
5132 }
5133
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005134 // Ignore touches if stylus is down anywhere on screen
5135 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5136 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5137 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5138 return false;
5139 }
5140
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141 return true;
5142}
5143
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005144std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5145 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005146 auto connectionIt = mConnectionsByToken.find(token);
5147 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005148 return nullptr;
5149 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005150 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005151}
5152
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005153void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005154 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5155 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005156 // Remove all handles on a display if there are no windows left.
5157 mWindowHandlesByDisplay.erase(displayId);
5158 return;
5159 }
5160
5161 // Since we compare the pointer of input window handles across window updates, we need
5162 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005163 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5164 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5165 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005166 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005167 }
5168
chaviw98318de2021-05-19 16:45:23 -05005169 std::vector<sp<WindowInfoHandle>> newHandles;
5170 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005171 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005172 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005173 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005174 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005175 const bool canReceiveInput =
5176 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5177 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005178 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005179 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005180 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005181 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005182 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005183 }
5184
5185 if (info->displayId != displayId) {
5186 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5187 handle->getName().c_str(), displayId, info->displayId);
5188 continue;
5189 }
5190
Robert Carredd13602020-04-13 17:24:34 -07005191 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5192 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005193 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005194 oldHandle->updateFrom(handle);
5195 newHandles.push_back(oldHandle);
5196 } else {
5197 newHandles.push_back(handle);
5198 }
5199 }
5200
5201 // Insert or replace
5202 mWindowHandlesByDisplay[displayId] = newHandles;
5203}
5204
Arthur Hungb92218b2018-08-14 12:00:21 +08005205/**
5206 * Called from InputManagerService, update window handle list by displayId that can receive input.
5207 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5208 * If set an empty list, remove all handles from the specific display.
5209 * For focused handle, check if need to change and send a cancel event to previous one.
5210 * For removed handle, check if need to send a cancel event if already in touch.
5211 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005212void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005213 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005214 if (DEBUG_FOCUS) {
5215 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005216 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005217 windowList += iwh->getName() + " ";
5218 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005219 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Prabir Pradhand65552b2021-10-07 11:23:50 -07005222 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005223 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005224 const WindowInfo& info = *window->getInfo();
5225
5226 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005227 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005228 if (noInputWindow && window->getToken() != nullptr) {
5229 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5230 window->getName().c_str());
5231 window->releaseChannel();
5232 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005233
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005234 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005235 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5236 !info.inputConfig.test(
5237 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005238 "%s has feature SPY, but is not a trusted overlay.",
5239 window->getName().c_str());
5240
Prabir Pradhand65552b2021-10-07 11:23:50 -07005241 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005242 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5243 !info.inputConfig.test(
5244 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005245 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5246 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005247 }
5248
Arthur Hung72d8dc32020-03-28 00:48:39 +00005249 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005250 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
chaviw98318de2021-05-19 16:45:23 -05005252 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005253
chaviw98318de2021-05-19 16:45:23 -05005254 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005255
Vishnu Nairc519ff72021-01-21 08:23:08 -08005256 std::optional<FocusResolver::FocusChanges> changes =
5257 mFocusResolver.setInputWindows(displayId, windowHandles);
5258 if (changes) {
5259 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005262 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5263 mTouchStatesByDisplay.find(displayId);
5264 if (stateIt != mTouchStatesByDisplay.end()) {
5265 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005266 for (size_t i = 0; i < state.windows.size();) {
5267 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005268 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005269 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5270 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005271 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005272 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5273 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005274 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005275 "touched window was removed");
5276 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005277 // Since we are about to drop the touch, cancel the events for the wallpaper as
5278 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005279 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005280 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5281 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005282 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005283 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005286 state.windows.erase(state.windows.begin() + i);
5287 } else {
5288 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 }
5290 }
arthurhungb89ccb02020-12-30 16:19:01 +08005291
arthurhung6d4bed92021-03-17 11:59:33 +08005292 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005293 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005294 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005295 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005296 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005297 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5298 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005299 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005300 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005301 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005302
Arthur Hung72d8dc32020-03-28 00:48:39 +00005303 // Release information for windows that are no longer present.
5304 // This ensures that unused input channels are released promptly.
5305 // Otherwise, they might stick around until the window handle is destroyed
5306 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005307 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005308 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005309 if (DEBUG_FOCUS) {
5310 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005311 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005312 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005313 }
chaviw291d88a2019-02-14 10:33:58 -08005314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315}
5316
5317void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005318 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005319 if (DEBUG_FOCUS) {
5320 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5321 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5322 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005323 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005324 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005325 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 } // release lock
5327
5328 // Wake up poll loop since it may need to make new input dispatching choices.
5329 mLooper->wake();
5330}
5331
Vishnu Nair599f1412021-06-21 10:39:58 -07005332void InputDispatcher::setFocusedApplicationLocked(
5333 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5334 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5335 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5336
5337 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5338 return; // This application is already focused. No need to wake up or change anything.
5339 }
5340
5341 // Set the new application handle.
5342 if (inputApplicationHandle != nullptr) {
5343 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5344 } else {
5345 mFocusedApplicationHandlesByDisplay.erase(displayId);
5346 }
5347
5348 // No matter what the old focused application was, stop waiting on it because it is
5349 // no longer focused.
5350 resetNoFocusedWindowTimeoutLocked();
5351}
5352
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005353void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5354 if (interval.count() < 0) {
5355 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5356 }
5357 std::scoped_lock _l(mLock);
5358 mMinTimeBetweenUserActivityPokes = interval;
5359}
5360
Tiger Huang721e26f2018-07-24 22:26:19 +08005361/**
5362 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5363 * the display not specified.
5364 *
5365 * We track any unreleased events for each window. If a window loses the ability to receive the
5366 * released event, we will send a cancel event to it. So when the focused display is changed, we
5367 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5368 * display. The display-specified events won't be affected.
5369 */
5370void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005371 if (DEBUG_FOCUS) {
5372 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5373 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005374 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005375 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005376
5377 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005378 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005379 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005380 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005381 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005382 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005383 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005385 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005386 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005387 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005388 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5389 }
5390 }
5391 mFocusedDisplayId = displayId;
5392
Chris Ye3c2d6f52020-08-09 10:39:48 -07005393 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005394 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005395 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005396
Vishnu Nairad321cd2020-08-20 16:40:21 -07005397 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005398 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005399 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005400 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005401 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005402 }
5403 }
5404 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005405 } // release lock
5406
5407 // Wake up poll loop since it may need to make new input dispatching choices.
5408 mLooper->wake();
5409}
5410
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005412 if (DEBUG_FOCUS) {
5413 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415
5416 bool changed;
5417 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005418 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419
5420 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5421 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005422 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005423 }
5424
5425 if (mDispatchEnabled && !enabled) {
5426 resetAndDropEverythingLocked("dispatcher is being disabled");
5427 }
5428
5429 mDispatchEnabled = enabled;
5430 mDispatchFrozen = frozen;
5431 changed = true;
5432 } else {
5433 changed = false;
5434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 } // release lock
5436
5437 if (changed) {
5438 // Wake up poll loop since it may need to make new input dispatching choices.
5439 mLooper->wake();
5440 }
5441}
5442
5443void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005444 if (DEBUG_FOCUS) {
5445 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447
5448 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005449 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450
5451 if (mInputFilterEnabled == enabled) {
5452 return;
5453 }
5454
5455 mInputFilterEnabled = enabled;
5456 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5457 } // release lock
5458
5459 // Wake up poll loop since there might be work to do to drop everything.
5460 mLooper->wake();
5461}
5462
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005463bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005464 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005465 bool needWake = false;
5466 {
5467 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005468 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005469 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005470 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005471 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5472 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005473 mTouchModePerDisplay.count(displayId) == 0
5474 ? "not set"
5475 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5476
Antonio Kantek15beb512022-06-13 22:35:41 +00005477 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5478 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005479 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005480 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005481 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005482 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5483 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005484 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005485 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005486 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005487 return false;
5488 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005489 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005490 mTouchModePerDisplay[displayId] = inTouchMode;
5491 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5492 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005493 needWake = enqueueInboundEventLocked(std::move(entry));
5494 } // release lock
5495
5496 if (needWake) {
5497 mLooper->wake();
5498 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005499 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005500}
5501
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005502bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005503 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5504 if (focusedToken == nullptr) {
5505 return false;
5506 }
5507 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5508 return isWindowOwnedBy(windowHandle, pid, uid);
5509}
5510
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005511bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005512 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5513 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5514 const sp<WindowInfoHandle> windowHandle =
5515 getWindowHandleLocked(connectionToken);
5516 return isWindowOwnedBy(windowHandle, pid, uid);
5517 }) != mInteractionConnectionTokens.end();
5518}
5519
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005520void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5521 if (opacity < 0 || opacity > 1) {
5522 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5523 return;
5524 }
5525
5526 std::scoped_lock lock(mLock);
5527 mMaximumObscuringOpacityForTouch = opacity;
5528}
5529
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005530std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5531InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005532 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5533 for (TouchedWindow& w : state.windows) {
5534 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005535 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005536 }
5537 }
5538 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005539 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005540}
5541
arthurhungb89ccb02020-12-30 16:19:01 +08005542bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5543 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005544 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005545 if (DEBUG_FOCUS) {
5546 ALOGD("Trivial transfer to same window.");
5547 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005548 return true;
5549 }
5550
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005552 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553
Arthur Hungabbb9d82021-09-01 14:52:30 +00005554 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005555 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005556
Arthur Hungabbb9d82021-09-01 14:52:30 +00005557 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005558 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 return false;
5560 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005561 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5562 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005563 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5564 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005565 return false;
5566 }
5567 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005568
Arthur Hungabbb9d82021-09-01 14:52:30 +00005569 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5570 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005571 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005572 return false;
5573 }
5574
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005575 if (DEBUG_FOCUS) {
5576 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005577 touchedWindow->windowHandle->getName().c_str(),
5578 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 }
5580
Arthur Hungabbb9d82021-09-01 14:52:30 +00005581 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005582 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005583 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005584 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005585 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
Arthur Hungabbb9d82021-09-01 14:52:30 +00005587 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005588 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005589 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005590 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005591 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005592 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005593 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005594 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005595 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596
Arthur Hungabbb9d82021-09-01 14:52:30 +00005597 // Store the dragging window.
5598 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005599 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005600 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5601 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005602 return false;
5603 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005604 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005605 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005606 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 }
5608
Arthur Hungabbb9d82021-09-01 14:52:30 +00005609 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005610 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5611 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005612 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005613 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005614 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5615 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005617 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5618 newTargetFlags);
5619
5620 // Check if the wallpaper window should deliver the corresponding event.
5621 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005622 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 } // release lock
5625
5626 // Wake up poll loop since it may need to make new input dispatching choices.
5627 mLooper->wake();
5628 return true;
5629}
5630
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005631/**
5632 * Get the touched foreground window on the given display.
5633 * Return null if there are no windows touched on that display, or if more than one foreground
5634 * window is being touched.
5635 */
5636sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5637 auto stateIt = mTouchStatesByDisplay.find(displayId);
5638 if (stateIt == mTouchStatesByDisplay.end()) {
5639 ALOGI("No touch state on display %" PRId32, displayId);
5640 return nullptr;
5641 }
5642
5643 const TouchState& state = stateIt->second;
5644 sp<WindowInfoHandle> touchedForegroundWindow;
5645 // If multiple foreground windows are touched, return nullptr
5646 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005647 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005648 if (touchedForegroundWindow != nullptr) {
5649 ALOGI("Two or more foreground windows: %s and %s",
5650 touchedForegroundWindow->getName().c_str(),
5651 window.windowHandle->getName().c_str());
5652 return nullptr;
5653 }
5654 touchedForegroundWindow = window.windowHandle;
5655 }
5656 }
5657 return touchedForegroundWindow;
5658}
5659
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005660// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005661bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005662 sp<IBinder> fromToken;
5663 { // acquire lock
5664 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005665 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005666 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005667 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5668 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005669 return false;
5670 }
5671
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005672 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5673 if (from == nullptr) {
5674 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5675 return false;
5676 }
5677
5678 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005679 } // release lock
5680
5681 return transferTouchFocus(fromToken, destChannelToken);
5682}
5683
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005685 if (DEBUG_FOCUS) {
5686 ALOGD("Resetting and dropping all events (%s).", reason);
5687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688
Michael Wrightfb04fd52022-11-24 22:31:11 +00005689 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 synthesizeCancelationEventsForAllConnectionsLocked(options);
5691
5692 resetKeyRepeatLocked();
5693 releasePendingEventLocked();
5694 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005695 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005697 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005698 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699}
5700
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005701void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 dumpDispatchStateLocked(dump);
5704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 std::istringstream stream(dump);
5706 std::string line;
5707
5708 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005709 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 }
5711}
5712
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005713std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005714 std::string dump;
5715
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005716 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5717 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005718
5719 std::string windowName = "None";
5720 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005721 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005722 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5723 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5724 : "token has capture without window";
5725 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005726 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005727
5728 return dump;
5729}
5730
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005731void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005732 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5733 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5734 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005735 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736
Tiger Huang721e26f2018-07-24 22:26:19 +08005737 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5738 dump += StringPrintf(INDENT "FocusedApplications:\n");
5739 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5740 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005741 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005742 const std::chrono::duration timeout =
5743 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005744 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005745 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005746 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005749 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005751
Vishnu Nairc519ff72021-01-21 08:23:08 -08005752 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005753 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005755 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005756 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005757 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005758 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5759 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
5761 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005762 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 }
5764
arthurhung6d4bed92021-03-17 11:59:33 +08005765 if (mDragState) {
5766 dump += StringPrintf(INDENT "DragState:\n");
5767 mDragState->dump(dump, INDENT2);
5768 }
5769
Arthur Hungb92218b2018-08-14 12:00:21 +08005770 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005771 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5772 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5773 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5774 const auto& displayInfo = it->second;
5775 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5776 displayInfo.logicalHeight);
5777 displayInfo.transform.dump(dump, "transform", INDENT4);
5778 } else {
5779 dump += INDENT2 "No DisplayInfo found!\n";
5780 }
5781
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005782 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005783 dump += INDENT2 "Windows:\n";
5784 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005785 dump += StringPrintf(INDENT3 "%zu: %s", i,
5786 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005787 }
5788 } else {
5789 dump += INDENT2 "Windows: <none>\n";
5790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 }
5792 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005793 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794 }
5795
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005796 if (!mGlobalMonitorsByDisplay.empty()) {
5797 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5798 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005799 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 }
5804
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005805 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806
5807 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005808 if (!mRecentQueue.empty()) {
5809 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005810 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005811 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005812 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005813 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 }
5815 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005816 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
5819 // Dump event currently being dispatched.
5820 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005821 dump += INDENT "PendingEvent:\n";
5822 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005823 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005824 dump += StringPrintf(", age=%" PRId64 "ms\n",
5825 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005827 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 }
5829
5830 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005831 if (!mInboundQueue.empty()) {
5832 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005833 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005834 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005835 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005836 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 }
5838 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005839 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 }
5841
Prabir Pradhancef936d2021-07-21 16:17:52 +00005842 if (!mCommandQueue.empty()) {
5843 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5844 } else {
5845 dump += INDENT "CommandQueue: <empty>\n";
5846 }
5847
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005849 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005850 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005851 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005852 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005853 connection->inputChannel->getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005854 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005855 connection->getWindowName().c_str(),
5856 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005857 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005859 if (!connection->outboundQueue.empty()) {
5860 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5861 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005862 dump += dumpQueue(connection->outboundQueue, currentTime);
5863
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005865 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866 }
5867
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005868 if (!connection->waitQueue.empty()) {
5869 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5870 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005871 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005873 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005875 std::string inputStateDump = streamableToString(connection->inputState);
5876 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005877 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005878 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880 }
5881 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005882 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 }
5884
Antonio Kantek15beb512022-06-13 22:35:41 +00005885 if (!mTouchModePerDisplay.empty()) {
5886 dump += INDENT "TouchModePerDisplay:\n";
5887 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5888 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5889 std::to_string(touchMode).c_str());
5890 }
5891 } else {
5892 dump += INDENT "TouchModePerDisplay: <none>\n";
5893 }
5894
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005895 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005896 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5897 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5898 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005899 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005900 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005901 dump += INDENT "InputTracer: ";
5902 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903}
5904
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005905void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005906 const size_t numMonitors = monitors.size();
5907 for (size_t i = 0; i < numMonitors; i++) {
5908 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005909 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5911 dump += "\n";
5912 }
5913}
5914
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005915class LooperEventCallback : public LooperCallback {
5916public:
5917 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5918 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5919
5920private:
5921 std::function<int(int events)> mCallback;
5922};
5923
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005924Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005925 if (DEBUG_CHANNEL_CREATION) {
5926 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005929 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005930 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005931 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005932
5933 if (result) {
5934 return base::Error(result) << "Failed to open input channel pair with name " << name;
5935 }
5936
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005938 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005939 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005940 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005941 std::shared_ptr<Connection> connection =
5942 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5943 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005945 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5946 ALOGE("Created a new connection, but the token %p is already known", token.get());
5947 }
5948 mConnectionsByToken.emplace(token, connection);
5949
5950 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5951 this, std::placeholders::_1, token);
5952
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005953 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005954 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 } // release lock
5956
5957 // Wake the looper because some connections have changed.
5958 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005959 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960}
5961
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005962Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005963 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005964 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005965 std::shared_ptr<InputChannel> serverChannel;
5966 std::unique_ptr<InputChannel> clientChannel;
5967 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5968 if (result) {
5969 return base::Error(result) << "Failed to open input channel pair with name " << name;
5970 }
5971
Michael Wright3dd60e22019-03-27 22:06:44 +00005972 { // acquire lock
5973 std::scoped_lock _l(mLock);
5974
5975 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005976 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5977 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005978 }
5979
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005980 std::shared_ptr<Connection> connection =
5981 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005982 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005983 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005984
5985 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5986 ALOGE("Created a new connection, but the token %p is already known", token.get());
5987 }
5988 mConnectionsByToken.emplace(token, connection);
5989 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5990 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005991
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005992 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005993
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005994 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005995 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005996 }
Garfield Tan15601662020-09-22 15:32:38 -07005997
Michael Wright3dd60e22019-03-27 22:06:44 +00005998 // Wake the looper because some connections have changed.
5999 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07006000 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006001}
6002
Garfield Tan15601662020-09-22 15:32:38 -07006003status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006005 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006
Harry Cutts33476232023-01-30 19:57:29 +00006007 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006008 if (status) {
6009 return status;
6010 }
6011 } // release lock
6012
6013 // Wake the poll loop because removing the connection may have changed the current
6014 // synchronization state.
6015 mLooper->wake();
6016 return OK;
6017}
6018
Garfield Tan15601662020-09-22 15:32:38 -07006019status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6020 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006021 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006022 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006023 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 return BAD_VALUE;
6025 }
6026
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006027 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006028
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006030 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 }
6032
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08006033 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034
6035 nsecs_t currentTime = now();
6036 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6037
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006038 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 return OK;
6040}
6041
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006042void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006043 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6044 auto& [displayId, monitors] = *it;
6045 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6046 return monitor.inputChannel->getConnectionToken() == connectionToken;
6047 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006048
Michael Wright3dd60e22019-03-27 22:06:44 +00006049 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006050 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006051 } else {
6052 ++it;
6053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054 }
6055}
6056
Michael Wright3dd60e22019-03-27 22:06:44 +00006057status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006058 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006059 return pilferPointersLocked(token);
6060}
Michael Wright3dd60e22019-03-27 22:06:44 +00006061
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006062status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006063 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6064 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006065 LOG(WARNING)
6066 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006067 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006068 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006069
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006070 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006071 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006072 LOG(WARNING)
6073 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6074 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006075 return BAD_VALUE;
6076 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006077 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006078 if (deviceIds.empty()) {
6079 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006080 return BAD_VALUE;
6081 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006082
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006083 for (const DeviceId deviceId : deviceIds) {
6084 TouchState& state = *statePtr;
6085 TouchedWindow& window = *windowPtr;
6086 // Send cancel events to all the input channels we're stealing from.
6087 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6088 "input channel stole pointer stream");
6089 options.deviceId = deviceId;
6090 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006091 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6092 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006093 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006094
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006095 std::string canceledWindows;
6096 for (const TouchedWindow& w : state.windows) {
6097 const std::shared_ptr<InputChannel> channel =
6098 getInputChannelLocked(w.windowHandle->getToken());
6099 if (channel != nullptr && channel->getConnectionToken() != token) {
6100 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6101 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6102 canceledWindows += channel->getName();
6103 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006104 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006105 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6106 LOG(INFO) << "Channel " << requestingChannel->getName()
6107 << " is stealing input gesture for device " << deviceId << " from "
6108 << canceledWindows;
6109
6110 // Prevent the gesture from being sent to any other windows.
6111 // This only blocks relevant pointers to be sent to other windows
6112 window.addPilferingPointers(deviceId, pointerIds);
6113
6114 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006115 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006116 return OK;
6117}
6118
Prabir Pradhan99987712020-11-10 18:43:05 -08006119void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6120 { // acquire lock
6121 std::scoped_lock _l(mLock);
6122 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006123 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006124 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6125 windowHandle != nullptr ? windowHandle->getName().c_str()
6126 : "token without window");
6127 }
6128
Vishnu Nairc519ff72021-01-21 08:23:08 -08006129 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006130 if (focusedToken != windowToken) {
6131 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6132 enabled ? "enable" : "disable");
6133 return;
6134 }
6135
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006136 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006137 ALOGW("Ignoring request to %s Pointer Capture: "
6138 "window has %s requested pointer capture.",
6139 enabled ? "enable" : "disable", enabled ? "already" : "not");
6140 return;
6141 }
6142
Christine Franksb768bb42021-11-29 12:11:31 -08006143 if (enabled) {
6144 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6145 mIneligibleDisplaysForPointerCapture.end(),
6146 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6147 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6148 return;
6149 }
6150 }
6151
Prabir Pradhan99987712020-11-10 18:43:05 -08006152 setPointerCaptureLocked(enabled);
6153 } // release lock
6154
6155 // Wake the thread to process command entries.
6156 mLooper->wake();
6157}
6158
Christine Franksb768bb42021-11-29 12:11:31 -08006159void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6160 { // acquire lock
6161 std::scoped_lock _l(mLock);
6162 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6163 if (!isEligible) {
6164 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6165 }
6166 } // release lock
6167}
6168
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006169std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006170 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006171 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006172 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006173 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006174 }
6175 }
6176 }
6177 return std::nullopt;
6178}
6179
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006180std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6181 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006182 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006183 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006184 }
6185
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006186 for (const auto& [token, connection] : mConnectionsByToken) {
6187 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006188 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 }
6190 }
Robert Carr4e670e52018-08-15 13:26:12 -07006191
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006192 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006193}
6194
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006195std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006196 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006197 if (connection == nullptr) {
6198 return "<nullptr>";
6199 }
6200 return connection->getInputChannelName();
6201}
6202
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006203void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006204 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006205 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006206}
6207
Prabir Pradhancef936d2021-07-21 16:17:52 +00006208void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006209 const std::shared_ptr<Connection>& connection,
6210 uint32_t seq, bool handled,
6211 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006212 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006213 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006214
6215 { // Start critical section
6216 auto dispatchEntryIt =
6217 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6218 [seq](auto& e) { return e->seq == seq; });
6219 if (dispatchEntryIt == connection->waitQueue.end()) {
6220 return;
6221 }
6222
6223 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6224
6225 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6226 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6227 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6228 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6229 }
6230 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6231 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6232 connection->inputChannel->getConnectionToken(),
6233 dispatchEntry.deliveryTime, consumeTime, finishTime);
6234 }
6235
6236 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006237 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6238 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006239 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006240 }
6241 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242
6243 // Dequeue the event and start the next cycle.
6244 // Because the lock might have been released, it is possible that the
6245 // contents of the wait queue to have been drained, so we need to double-check
6246 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006247 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6248 [seq](auto& e) { return e->seq == seq; });
6249 if (entryIt != connection->waitQueue.end()) {
6250 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6251 connection->waitQueue.erase(entryIt);
6252
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6254 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6255 if (!connection->responsive) {
6256 connection->responsive = isConnectionResponsive(*connection);
6257 if (connection->responsive) {
6258 // The connection was unresponsive, and now it's responsive.
6259 processConnectionResponsiveLocked(*connection);
6260 }
6261 }
6262 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006263 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6264 const InputTarget target{.inputChannel = connection->inputChannel,
6265 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006266 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006267 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006268 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269 }
6270
6271 // Start the next dispatch cycle for this connection.
6272 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273}
6274
Prabir Pradhancef936d2021-07-21 16:17:52 +00006275void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6276 const sp<IBinder>& newToken) {
6277 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6278 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006279 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006280 };
6281 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282}
6283
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6285 auto command = [this, token, x, y]() REQUIRES(mLock) {
6286 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006287 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006288 };
6289 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006290}
6291
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006292void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006293 if (connection == nullptr) {
6294 LOG_ALWAYS_FATAL("Caller must check for nullness");
6295 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006296 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6297 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006298 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006299 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006301 return;
6302 }
6303 /**
6304 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6305 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6306 * has changed. This could cause newer entries to time out before the already dispatched
6307 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6308 * processes the events linearly. So providing information about the oldest entry seems to be
6309 * most useful.
6310 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006311 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6312 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006313 std::string reason =
6314 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006316 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006317 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006318 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006319 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006321 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6322
6323 // Stop waking up for events on this connection, it is already unresponsive
6324 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006325}
6326
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006327void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6328 std::string reason =
6329 StringPrintf("%s does not have a focused window", application->getName().c_str());
6330 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006331
Yabin Cui8eb9c552023-06-08 18:05:07 +00006332 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006334 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006335 };
6336 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006337}
6338
chaviw98318de2021-05-19 16:45:23 -05006339void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006340 const std::string& reason) {
6341 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6342 updateLastAnrStateLocked(windowLabel, reason);
6343}
6344
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006345void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6346 const std::string& reason) {
6347 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006348 updateLastAnrStateLocked(windowLabel, reason);
6349}
6350
6351void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6352 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006354 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355 struct tm tm;
6356 localtime_r(&t, &tm);
6357 char timestr[64];
6358 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006359 mLastAnrState.clear();
6360 mLastAnrState += INDENT "ANR:\n";
6361 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006362 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6363 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006364 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365}
6366
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006368 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 const KeyEvent event = createKeyEvent(entry);
6370 nsecs_t delay = 0;
6371 { // release lock
6372 scoped_unlock unlock(mLock);
6373 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006374 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006375 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6376 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6377 std::to_string(t.duration().count()).c_str());
6378 }
6379 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380
6381 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006382 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006383 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006384 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006386 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006387 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389}
6390
Prabir Pradhancef936d2021-07-21 16:17:52 +00006391void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006392 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006393 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006394 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006395 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006396 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006397 };
6398 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006399}
6400
Prabir Pradhanedd96402022-02-15 01:46:16 -08006401void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006402 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006403 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006405 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006406 };
6407 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006408}
6409
6410/**
6411 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6412 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6413 * command entry to the command queue.
6414 */
6415void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6416 std::string reason) {
6417 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006418 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006419 if (connection.monitor) {
6420 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6421 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006422 pid = findMonitorPidByTokenLocked(connectionToken);
6423 } else {
6424 // The connection is a window
6425 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6426 reason.c_str());
6427 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6428 if (handle != nullptr) {
6429 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006430 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006431 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006432 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006433}
6434
6435/**
6436 * Tell the policy that a connection has become responsive so that it can stop ANR.
6437 */
6438void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6439 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006440 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006441 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006442 pid = findMonitorPidByTokenLocked(connectionToken);
6443 } else {
6444 // The connection is a window
6445 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6446 if (handle != nullptr) {
6447 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006449 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006450 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006451}
6452
Prabir Pradhan24047542023-11-02 17:14:59 +00006453std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006454 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006455 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006456 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006457 if (!handled) {
6458 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006459 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006460 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006461 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464 // Get the fallback key state.
6465 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006466 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006467 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006468 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006469 connection->inputState.removeFallbackKey(originalKeyCode);
6470 }
6471
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006472 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006473 // If the application handles the original key for which we previously
6474 // generated a fallback or if the window is not a foreground window,
6475 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006476 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006477 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006478 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6479 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6480 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6481 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6482 keyEntry.policyFlags);
6483 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006484 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486
6487 mLock.unlock();
6488
Prabir Pradhana41d2442023-04-20 21:30:40 +00006489 if (const auto unhandledKeyFallback =
6490 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6491 event, keyEntry.policyFlags);
6492 unhandledKeyFallback) {
6493 event = *unhandledKeyFallback;
6494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495
6496 mLock.lock();
6497
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006498 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006499 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006500 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 "application handled the original non-fallback key "
6502 "or is no longer a foreground target, "
6503 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006504 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 connection->inputState.removeFallbackKey(originalKeyCode);
6508 }
6509 } else {
6510 // If the application did not handle a non-fallback key, first check
6511 // that we are in a good state to perform unhandled key event processing
6512 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006513 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006514 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006515 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6516 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6517 "since this is not an initial down. "
6518 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6519 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6520 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006521 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006523
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006524 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006525 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6526 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6527 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6528 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6529 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006530 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006531
6532 mLock.unlock();
6533
Prabir Pradhana41d2442023-04-20 21:30:40 +00006534 bool fallback = false;
6535 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6536 event, keyEntry.policyFlags);
6537 fb) {
6538 fallback = true;
6539 event = *fb;
6540 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006541
6542 mLock.lock();
6543
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006544 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006545 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006546 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547 }
6548
6549 // Latch the fallback keycode for this key on an initial down.
6550 // The fallback keycode cannot change at any other point in the lifecycle.
6551 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006553 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006554 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006555 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006556 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006557 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558 }
6559
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006560 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006561
6562 // Cancel the fallback key if the policy decides not to send it anymore.
6563 // We will continue to dispatch the key to the policy but we will no
6564 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006565 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6566 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6568 if (fallback) {
6569 ALOGD("Unhandled key event: Policy requested to send key %d"
6570 "as a fallback for %d, but on the DOWN it had requested "
6571 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006572 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006573 } else {
6574 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6575 "but on the DOWN it had requested to send %d. "
6576 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006577 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006578 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006580
Michael Wrightfb04fd52022-11-24 22:31:11 +00006581 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006582 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006583 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006584 synthesizeCancelationEventsForConnectionLocked(connection, options);
6585
6586 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006587 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006588 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006589 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006590 }
6591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006593 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6594 {
6595 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006596 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006597 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006598 for (const auto& [key, value] : fallbackKeys) {
6599 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006600 }
6601 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6602 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006604 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006605
6606 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006607 // Return the fallback key that we want dispatched to the channel.
6608 std::unique_ptr<KeyEntry> newEntry =
6609 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6610 event.getEventTime(), event.getDeviceId(),
6611 event.getSource(), event.getDisplayId(),
6612 keyEntry.policyFlags, keyEntry.action,
6613 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6614 *fallbackKeyCode, event.getScanCode(),
6615 event.getMetaState(), event.getRepeatCount(),
6616 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006617 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6618 ALOGD("Unhandled key event: Dispatching fallback key. "
6619 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006620 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006621 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006622 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006623 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6625 ALOGD("Unhandled key event: No fallback key.");
6626 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006627
6628 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006629 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 }
6631 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006632 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006633}
6634
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635void InputDispatcher::traceInboundQueueLengthLocked() {
6636 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006637 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006638 }
6639}
6640
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006641void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006642 if (ATRACE_ENABLED()) {
6643 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006644 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6645 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006646 }
6647}
6648
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006649void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006650 if (ATRACE_ENABLED()) {
6651 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006652 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6653 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006654 }
6655}
6656
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006657void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006658 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006659
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006660 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006661 dumpDispatchStateLocked(dump);
6662
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006663 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006664 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006665 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666 }
6667}
6668
6669void InputDispatcher::monitor() {
6670 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006671 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006673 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674}
6675
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006676/**
6677 * Wake up the dispatcher and wait until it processes all events and commands.
6678 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6679 * this method can be safely called from any thread, as long as you've ensured that
6680 * the work you are interested in completing has already been queued.
6681 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006682bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006683 /**
6684 * Timeout should represent the longest possible time that a device might spend processing
6685 * events and commands.
6686 */
6687 constexpr std::chrono::duration TIMEOUT = 100ms;
6688 std::unique_lock lock(mLock);
6689 mLooper->wake();
6690 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6691 return result == std::cv_status::no_timeout;
6692}
6693
Vishnu Naire798b472020-07-23 13:52:21 -07006694/**
6695 * Sets focus to the window identified by the token. This must be called
6696 * after updating any input window handles.
6697 *
6698 * Params:
6699 * request.token - input channel token used to identify the window that should gain focus.
6700 * request.focusedToken - the token that the caller expects currently to be focused. If the
6701 * specified token does not match the currently focused window, this request will be dropped.
6702 * If the specified focused token matches the currently focused window, the call will succeed.
6703 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6704 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6705 * when requesting the focus change. This determines which request gets
6706 * precedence if there is a focus change request from another source such as pointer down.
6707 */
Vishnu Nair958da932020-08-21 17:12:37 -07006708void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6709 { // acquire lock
6710 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006711 std::optional<FocusResolver::FocusChanges> changes =
6712 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6713 if (changes) {
6714 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006715 }
6716 } // release lock
6717 // Wake up poll loop since it may need to make new input dispatching choices.
6718 mLooper->wake();
6719}
6720
Vishnu Nairc519ff72021-01-21 08:23:08 -08006721void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6722 if (changes.oldFocus) {
6723 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006724 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006725 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006726 "focus left window");
6727 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006728 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006729 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006730 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006731 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006732 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006733 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006734 }
6735
Prabir Pradhan99987712020-11-10 18:43:05 -08006736 // If a window has pointer capture, then it must have focus. We need to ensure that this
6737 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6738 // If the window loses focus before it loses pointer capture, then the window can be in a state
6739 // where it has pointer capture but not focus, violating the contract. Therefore we must
6740 // dispatch the pointer capture event before the focus event. Since focus events are added to
6741 // the front of the queue (above), we add the pointer capture event to the front of the queue
6742 // after the focus events are added. This ensures the pointer capture event ends up at the
6743 // front.
6744 disablePointerCaptureForcedLocked();
6745
Vishnu Nairc519ff72021-01-21 08:23:08 -08006746 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006747 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006748 }
6749}
Vishnu Nair958da932020-08-21 17:12:37 -07006750
Prabir Pradhan99987712020-11-10 18:43:05 -08006751void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006752 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006753 return;
6754 }
6755
6756 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6757
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006758 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006759 setPointerCaptureLocked(false);
6760 }
6761
6762 if (!mWindowTokenWithPointerCapture) {
6763 // No need to send capture changes because no window has capture.
6764 return;
6765 }
6766
6767 if (mPendingEvent != nullptr) {
6768 // Move the pending event to the front of the queue. This will give the chance
6769 // for the pending event to be dropped if it is a captured event.
6770 mInboundQueue.push_front(mPendingEvent);
6771 mPendingEvent = nullptr;
6772 }
6773
6774 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006775 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006776 mInboundQueue.push_front(std::move(entry));
6777}
6778
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006779void InputDispatcher::setPointerCaptureLocked(bool enable) {
6780 mCurrentPointerCaptureRequest.enable = enable;
6781 mCurrentPointerCaptureRequest.seq++;
6782 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006783 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006784 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006785 };
6786 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006787}
6788
Vishnu Nair599f1412021-06-21 10:39:58 -07006789void InputDispatcher::displayRemoved(int32_t displayId) {
6790 { // acquire lock
6791 std::scoped_lock _l(mLock);
6792 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006793 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006794 setFocusedApplicationLocked(displayId, nullptr);
6795 // Call focus resolver to clean up stale requests. This must be called after input windows
6796 // have been removed for the removed display.
6797 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006798 // Reset pointer capture eligibility, regardless of previous state.
6799 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006800 // Remove the associated touch mode state.
6801 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006802 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006803 } // release lock
6804
6805 // Wake up poll loop since it may need to make new input dispatching choices.
6806 mLooper->wake();
6807}
6808
Patrick Williamsd828f302023-04-28 17:52:08 -05006809void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006810 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6811 {
6812 // acquire lock
6813 std::scoped_lock _l(mLock);
6814 logDispatchStateLocked();
6815 }
6816 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6817 result.error().message().c_str());
6818 };
chaviw15fab6f2021-06-07 14:15:52 -05006819 // The listener sends the windows as a flattened array. Separate the windows by display for
6820 // more convenient parsing.
6821 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006822 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006823 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006824 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006825 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006826
6827 { // acquire lock
6828 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006829
6830 // Ensure that we have an entry created for all existing displays so that if a displayId has
6831 // no windows, we can tell that the windows were removed from the display.
6832 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6833 handlesPerDisplay[displayId];
6834 }
6835
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006836 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006837 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006838 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6839 }
6840
6841 for (const auto& [displayId, handles] : handlesPerDisplay) {
6842 setInputWindowsLocked(handles, displayId);
6843 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006844
6845 if (update.vsyncId < mWindowInfosVsyncId) {
6846 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6847 ", current update vsync id: %" PRId64,
6848 mWindowInfosVsyncId, update.vsyncId);
6849 }
6850 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006851 }
6852 // Wake up poll loop since it may need to make new input dispatching choices.
6853 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006854}
6855
Vishnu Nair062a8672021-09-03 16:07:44 -07006856bool InputDispatcher::shouldDropInput(
6857 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006858 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6859 (windowHandle->getInfo()->inputConfig.test(
6860 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006861 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006862 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6863 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006864 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006865 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006866 windowHandle->getInfo()->displayId);
6867 return true;
6868 }
6869 return false;
6870}
6871
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006872void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006873 const gui::WindowInfosUpdate& update) {
6874 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006875}
6876
Arthur Hungdfd528e2021-12-08 13:23:04 +00006877void InputDispatcher::cancelCurrentTouch() {
6878 {
6879 std::scoped_lock _l(mLock);
6880 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006881 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006882 "cancel current touch");
6883 synthesizeCancelationEventsForAllConnectionsLocked(options);
6884
6885 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006886 }
6887 // Wake up poll loop since there might be work to do.
6888 mLooper->wake();
6889}
6890
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006891void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6892 std::scoped_lock _l(mLock);
6893 mMonitorDispatchingTimeout = timeout;
6894}
6895
Arthur Hungc539dbb2022-12-08 07:45:36 +00006896void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6897 const sp<WindowInfoHandle>& oldWindowHandle,
6898 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006899 TouchState& state, int32_t deviceId,
6900 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006901 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006902 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006903 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6904 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6905 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6906 newWindowHandle->getInfo()->inputConfig.test(
6907 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6908 const sp<WindowInfoHandle> oldWallpaper =
6909 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6910 const sp<WindowInfoHandle> newWallpaper =
6911 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6912 if (oldWallpaper == newWallpaper) {
6913 return;
6914 }
6915
6916 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006917 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006918 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006919 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006920 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006921 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006922 }
6923
6924 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006925 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6926 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006927 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006928 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006929 }
6930}
6931
6932void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6933 ftl::Flags<InputTarget::Flags> newTargetFlags,
6934 const sp<WindowInfoHandle> fromWindowHandle,
6935 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006936 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006937 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006938 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6939 fromWindowHandle->getInfo()->inputConfig.test(
6940 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6941 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6942 toWindowHandle->getInfo()->inputConfig.test(
6943 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6944
6945 const sp<WindowInfoHandle> oldWallpaper =
6946 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6947 const sp<WindowInfoHandle> newWallpaper =
6948 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6949 if (oldWallpaper == newWallpaper) {
6950 return;
6951 }
6952
6953 if (oldWallpaper != nullptr) {
6954 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6955 "transferring touch focus to another window");
6956 state.removeWindowByToken(oldWallpaper->getToken());
6957 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6958 }
6959
6960 if (newWallpaper != nullptr) {
6961 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006962 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006963 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6964 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006965 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006966 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006967 std::shared_ptr<Connection> wallpaperConnection =
6968 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006969 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006970 std::shared_ptr<Connection> toConnection =
6971 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006972 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6973 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6974 wallpaperFlags);
6975 }
6976 }
6977}
6978
6979sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6980 const sp<WindowInfoHandle>& windowHandle) const {
6981 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6982 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6983 bool foundWindow = false;
6984 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6985 if (!foundWindow && otherHandle != windowHandle) {
6986 continue;
6987 }
6988 if (windowHandle == otherHandle) {
6989 foundWindow = true;
6990 continue;
6991 }
6992
6993 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6994 return otherHandle;
6995 }
6996 }
6997 return nullptr;
6998}
6999
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007000void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7001 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007002 std::scoped_lock _l(mLock);
7003
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007004 mConfig.keyRepeatTimeout = timeout.count();
7005 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007006}
7007
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007008bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7009 DeviceId deviceId, int32_t pointerId) {
7010 std::scoped_lock _l(mLock);
7011 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7012 if (touchStateIt == mTouchStatesByDisplay.end()) {
7013 return false;
7014 }
7015 for (const TouchedWindow& window : touchStateIt->second.windows) {
7016 if (window.windowHandle->getToken() == token &&
7017 (window.hasTouchingPointer(deviceId, pointerId) ||
7018 window.hasHoveringPointer(deviceId, pointerId))) {
7019 return true;
7020 }
7021 }
7022 return false;
7023}
7024
Garfield Tane84e6f92019-08-29 17:28:41 -07007025} // namespace android::inputdispatcher