blob: d46c0598e3d11ce02a30a5d42a3e6258de267d59 [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) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800731 return target.connection->getToken() == window.windowHandle->getToken();
Harry Cuttsb166c002023-05-09 13:06:05 +0000732 });
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;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800873 removeInputChannelLocked(connection->getToken(), /*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
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -0800993 mAnrTracker.eraseToken(connection->getToken());
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 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001003 const sp<WindowInfoHandle> window = getWindowHandleLocked(connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001005 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001006 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001007 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001008}
1009
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001010void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 nsecs_t currentTime = now();
1012
Jeff Browndc5992e2014-04-11 01:27:26 -07001013 // Reset the key repeat timer whenever normal dispatch is suspended while the
1014 // device is in a non-interactive state. This is to ensure that we abort a key
1015 // repeat if the device is just coming out of sleep.
1016 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 resetKeyRepeatLocked();
1018 }
1019
1020 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1021 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001022 if (DEBUG_FOCUS) {
1023 ALOGD("Dispatch frozen. Waiting some more.");
1024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 return;
1026 }
1027
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 // Ready to start a new event.
1029 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001031 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 // Synthesize a key repeat if appropriate.
1033 if (mKeyRepeatState.lastKeyEntry) {
1034 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1035 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1036 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001037 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039 }
1040
1041 // Nothing to do if there is no pending event.
1042 if (!mPendingEvent) {
1043 return;
1044 }
1045 } else {
1046 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001047 mPendingEvent = mInboundQueue.front();
1048 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 traceInboundQueueLengthLocked();
1050 }
1051
1052 // Poke user activity for this event.
1053 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001054 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057
1058 // Now we have an event to dispatch.
1059 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001060 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001062 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001064 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068
1069 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072
1073 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001074 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075 const ConfigurationChangedEntry& typedEntry =
1076 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 break;
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001082 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001083 const DeviceResetEntry& typedEntry =
1084 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 break;
1088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001090 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001091 std::shared_ptr<const FocusEntry> typedEntry =
1092 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001093 dispatchFocusLocked(currentTime, typedEntry);
1094 done = true;
1095 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1096 break;
1097 }
1098
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001099 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001100 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001101 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1102 done = true;
1103 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1104 break;
1105 }
1106
Prabir Pradhan99987712020-11-10 18:43:05 -08001107 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1108 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001109 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001110 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1111 done = true;
1112 break;
1113 }
1114
arthurhungb89ccb02020-12-30 16:19:01 +08001115 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001116 std::shared_ptr<const DragEntry> typedEntry =
1117 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001118 dispatchDragLocked(currentTime, typedEntry);
1119 done = true;
1120 break;
1121 }
1122
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001123 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001124 std::shared_ptr<const KeyEntry> keyEntry =
1125 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001127 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1130 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001132 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001133 if (done && mTracer) {
1134 ensureEventTraced(*keyEntry);
1135 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1136 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 break;
1138 }
1139
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001141 std::shared_ptr<const MotionEntry> motionEntry =
1142 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001144 // The event is stale. However, only drop stale events if there isn't an ongoing
1145 // gesture. That would allow us to complete the processing of the current stroke.
1146 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1147 if (touchStateIt != mTouchStatesByDisplay.end()) {
1148 const TouchState& touchState = touchStateIt->second;
1149 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1150 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1151 dropReason = DropReason::STALE;
1152 }
1153 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001156 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1157 // Only drop events that are focus-dispatched.
1158 dropReason = DropReason::BLOCKED;
1159 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001162 if (done && mTracer) {
1163 ensureEventTraced(*motionEntry);
1164 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
Chris Yef59a2f42020-10-16 12:55:26 -07001168
1169 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001170 std::shared_ptr<const SensorEntry> sensorEntry =
1171 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001172
Chris Yef59a2f42020-10-16 12:55:26 -07001173 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1174 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1175 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1176 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1177 dropReason = DropReason::STALE;
1178 }
1179 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1180 done = true;
1181 break;
1182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184
1185 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001186 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001187 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 }
Michael Wright3a981722015-06-10 15:26:13 +01001189 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190
1191 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001192 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194}
1195
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001196bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001197 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001198}
1199
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200/**
1201 * Return true if the events preceding this incoming motion event should be dropped
1202 * Return false otherwise (the default behaviour)
1203 */
1204bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001205 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001206 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001207
1208 // Optimize case where the current application is unresponsive and the user
1209 // decides to touch a window in a different application.
1210 // If the application takes too long to catch up then we drop all events preceding
1211 // the touch into the other window.
1212 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001213 const int32_t displayId = motionEntry.displayId;
1214 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001215 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001216
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001217 sp<WindowInfoHandle> touchedWindowHandle =
1218 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001219 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220 touchedWindowHandle->getApplicationToken() !=
1221 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001223 ALOGI("Pruning input queue because user touched a different application while waiting "
1224 "for %s",
1225 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001226 return true;
1227 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001228
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001229 // Alternatively, maybe there's a spy window that could handle this event.
1230 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1231 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1232 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001233 const std::shared_ptr<Connection> connection =
1234 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001235 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001236 // This spy window could take more input. Drop all events preceding this
1237 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001238 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001239 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001240 mAwaitedFocusedApplication->getName().c_str());
1241 return true;
1242 }
1243 }
1244 }
1245
1246 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1247 // yet been processed by some connections, the dispatcher will wait for these motion
1248 // events to be processed before dispatching the key event. This is because these motion events
1249 // may cause a new window to be launched, which the user might expect to receive focus.
1250 // To prevent waiting forever for such events, just send the key to the currently focused window
1251 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1252 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1253 "just send the pending key event to the focused window.");
1254 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001255 }
1256 return false;
1257}
1258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001259bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001260 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001262 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 traceInboundQueueLengthLocked();
1264
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001266 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001267 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1268 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001271 if (mTracer) {
1272 ensureEventTraced(keyEntry);
1273 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001274
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001275 // If a new up event comes in, and the pending event with same key code has been asked
1276 // to try again later because of the policy. We have to reset the intercept key wake up
1277 // time for it may have been handled in the policy and could be dropped.
1278 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1279 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001280 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001281 if (pendingKey.keyCode == keyEntry.keyCode &&
1282 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001283 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1284 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001285 pendingKey.interceptKeyWakeupTime = 0;
1286 needWake = true;
1287 }
1288 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 break;
1290 }
1291
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001292 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001293 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1294 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001295 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1296 if (mTracer) {
1297 ensureEventTraced(motionEntry);
1298 }
1299 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001301 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001305 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001306 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1307 break;
1308 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001309 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001310 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001311 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001312 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001313 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1314 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001315 // nothing to do
1316 break;
1317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
1319
1320 return needWake;
1321}
1322
Prabir Pradhan24047542023-11-02 17:14:59 +00001323void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001324 // Do not store sensor event in recent queue to avoid flooding the queue.
1325 if (entry->type != EventEntry::Type::SENSOR) {
1326 mRecentQueue.push_back(entry);
1327 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001328 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001329 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 }
1331}
1332
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001333sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1334 bool isStylus,
1335 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001337 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001338 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001339 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001340 continue;
1341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001343 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001344 if (!info.isSpy() &&
1345 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001346 return windowHandle;
1347 }
1348 }
1349 return nullptr;
1350}
1351
1352std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001353 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001354 if (touchedWindow == nullptr) {
1355 return {};
1356 }
1357 // Traverse windows from front to back until we encounter the touched window.
1358 std::vector<InputTarget> outsideTargets;
1359 const auto& windowHandles = getWindowHandlesLocked(displayId);
1360 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1361 if (windowHandle == touchedWindow) {
1362 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1363 // below the touched window will not get ACTION_OUTSIDE event.
1364 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001365 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001366
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001367 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001368 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001369 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1370 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001371 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1372 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001373 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 }
1375 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001376 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377}
1378
Prabir Pradhand65552b2021-10-07 11:23:50 -07001379std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001380 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001381 // Traverse windows from front to back and gather the touched spy windows.
1382 std::vector<sp<WindowInfoHandle>> spyWindows;
1383 const auto& windowHandles = getWindowHandlesLocked(displayId);
1384 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1385 const WindowInfo& info = *windowHandle->getInfo();
1386
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001387 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001388 continue;
1389 }
1390 if (!info.isSpy()) {
1391 // The first touched non-spy window was found, so return the spy windows touched so far.
1392 return spyWindows;
1393 }
1394 spyWindows.push_back(windowHandle);
1395 }
1396 return spyWindows;
1397}
1398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 const char* reason;
1401 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001402 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001403 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001404 ALOGD("Dropped event because policy consumed it.");
1405 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001406 reason = "inbound event was dropped because the policy consumed it";
1407 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001408 case DropReason::DISABLED:
1409 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 ALOGI("Dropped event because input dispatch is disabled.");
1411 }
1412 reason = "inbound event was dropped because input dispatch is disabled";
1413 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001414 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001415 LOG(INFO) << "Dropping because the current application is not responding and the user "
1416 "has started interacting with a different application: "
1417 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001418 reason = "inbound event was dropped because the current application is not responding "
1419 "and the user has started interacting with a different application";
1420 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001421 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 ALOGI("Dropped event because it is stale.");
1423 reason = "inbound event was dropped because it is stale";
1424 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001425 case DropReason::NO_POINTER_CAPTURE:
1426 ALOGI("Dropped event because there is no window with Pointer Capture.");
1427 reason = "inbound event was dropped because there is no window with Pointer Capture";
1428 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001429 case DropReason::NOT_DROPPED: {
1430 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 }
1434
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001435 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001436 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001437 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001438 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1439 options.displayId = keyEntry.displayId;
1440 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001444 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001445 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1446 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001447 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001448 options.displayId = motionEntry.displayId;
1449 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 synthesizeCancelationEventsForAllConnectionsLocked(options);
1451 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001452 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1453 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001454 options.displayId = motionEntry.displayId;
1455 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 synthesizeCancelationEventsForAllConnectionsLocked(options);
1457 }
1458 break;
1459 }
Chris Yef59a2f42020-10-16 12:55:26 -07001460 case EventEntry::Type::SENSOR: {
1461 break;
1462 }
arthurhungb89ccb02020-12-30 16:19:01 +08001463 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1464 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001465 break;
1466 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001467 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001468 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001469 case EventEntry::Type::CONFIGURATION_CHANGED:
1470 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001471 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001472 break;
1473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 }
1475}
1476
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001478 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479}
1480
Prabir Pradhancef936d2021-07-21 16:17:52 +00001481bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001482 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 return false;
1484 }
1485
1486 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001487 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001488 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001489 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1490 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001491 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 return true;
1493}
1494
Prabir Pradhancef936d2021-07-21 16:17:52 +00001495void InputDispatcher::postCommandLocked(Command&& command) {
1496 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497}
1498
1499void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001500 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001501 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001502 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 releaseInboundEventLocked(entry);
1504 }
1505 traceInboundQueueLengthLocked();
1506}
1507
1508void InputDispatcher::releasePendingEventLocked() {
1509 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513}
1514
Prabir Pradhan24047542023-11-02 17:14:59 +00001515void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001516 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001518 if (DEBUG_DISPATCH_CYCLE) {
1519 ALOGD("Injected inbound event was dropped.");
1520 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 }
1523 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001524 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527}
1528
1529void InputDispatcher::resetKeyRepeatLocked() {
1530 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001531 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
1533}
1534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001535std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001536 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537
Michael Wright2e732952014-09-24 13:26:59 -07001538 uint32_t policyFlags = entry->policyFlags &
1539 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001541 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001542 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1543 currentTime, entry->deviceId, entry->source,
1544 entry->displayId, policyFlags, entry->action, entry->flags,
1545 entry->keyCode, entry->scanCode, entry->metaState,
1546 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001549 if (mTracer) {
1550 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1551 }
1552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556}
1557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001560 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1561 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563
1564 // Reset key repeating in case a keyboard device was added or removed or something.
1565 resetKeyRepeatLocked();
1566
1567 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001568 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1569 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001570 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001571 };
1572 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 return true;
1574}
1575
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001576bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1577 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001578 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1579 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1580 entry.deviceId);
1581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582
liushenxiang42232912021-05-21 20:24:09 +08001583 // Reset key repeating in case a keyboard device was disabled or enabled.
1584 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1585 resetKeyRepeatLocked();
1586 }
1587
Michael Wrightfb04fd52022-11-24 22:31:11 +00001588 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001591
1592 // Remove all active pointers from this device
1593 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1594 touchState.removeAllPointersForDevice(entry.deviceId);
1595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 return true;
1597}
1598
Vishnu Nairad321cd2020-08-20 16:40:21 -07001599void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001600 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001601 if (mPendingEvent != nullptr) {
1602 // Move the pending event to the front of the queue. This will give the chance
1603 // for the pending event to get dispatched to the newly focused window
1604 mInboundQueue.push_front(mPendingEvent);
1605 mPendingEvent = nullptr;
1606 }
1607
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001608 std::unique_ptr<FocusEntry> focusEntry =
1609 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1610 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001611
1612 // This event should go to the front of the queue, but behind all other focus events
1613 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001614 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1615 [](const std::shared_ptr<const EventEntry>& event) {
1616 return event->type == EventEntry::Type::FOCUS;
1617 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001618
1619 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001620 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001621}
1622
Prabir Pradhan24047542023-11-02 17:14:59 +00001623void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1624 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001625 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
1626 if (connection == nullptr) {
1627 return; // Connection has gone away
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001628 }
1629 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001630 target.connection = connection;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001631 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001632 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001633 connection->getInputChannelName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001634 std::string reason = std::string("reason=").append(entry->reason);
1635 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001636 dispatchEventLocked(currentTime, entry, {target});
1637}
1638
Prabir Pradhan99987712020-11-10 18:43:05 -08001639void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001640 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001641 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001642 dropReason = DropReason::NOT_DROPPED;
1643
Prabir Pradhan99987712020-11-10 18:43:05 -08001644 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001645 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001646
1647 if (entry->pointerCaptureRequest.enable) {
1648 // Enable Pointer Capture.
1649 if (haveWindowWithPointerCapture &&
1650 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001651 // This can happen if pointer capture is disabled and re-enabled before we notify the
1652 // app of the state change, so there is no need to notify the app.
1653 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1654 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001655 }
1656 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001657 // This can happen if a window requests capture and immediately releases capture.
1658 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001659 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 return;
1661 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1663 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1664 return;
1665 }
1666
Vishnu Nairc519ff72021-01-21 08:23:08 -08001667 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001668 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1669 mWindowTokenWithPointerCapture = token;
1670 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001671 // Disable Pointer Capture.
1672 // We do not check if the sequence number matches for requests to disable Pointer Capture
1673 // for two reasons:
1674 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1675 // to disable capture with the same sequence number: one generated by
1676 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1677 // Capture being disabled in InputReader.
1678 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1679 // actual Pointer Capture state that affects events being generated by input devices is
1680 // in InputReader.
1681 if (!haveWindowWithPointerCapture) {
1682 // Pointer capture was already forcefully disabled because of focus change.
1683 dropReason = DropReason::NOT_DROPPED;
1684 return;
1685 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001686 token = mWindowTokenWithPointerCapture;
1687 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001688 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001689 setPointerCaptureLocked(false);
1690 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001691 }
1692
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001693 auto connection = getConnectionLocked(token);
1694 if (connection == nullptr) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001695 // Window has gone away, clean up Pointer Capture state.
1696 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001697 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001698 setPointerCaptureLocked(false);
1699 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001700 return;
1701 }
1702 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001703 target.connection = connection;
Prabir Pradhan99987712020-11-10 18:43:05 -08001704 entry->dispatchInProgress = true;
1705 dispatchEventLocked(currentTime, entry, {target});
1706
1707 dropReason = DropReason::NOT_DROPPED;
1708}
1709
Prabir Pradhan24047542023-11-02 17:14:59 +00001710void InputDispatcher::dispatchTouchModeChangeLocked(
1711 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001712 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001713 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001714 if (windowHandles.empty()) {
1715 return;
1716 }
1717 const std::vector<InputTarget> inputTargets =
1718 getInputTargetsFromWindowHandlesLocked(windowHandles);
1719 if (inputTargets.empty()) {
1720 return;
1721 }
1722 entry->dispatchInProgress = true;
1723 dispatchEventLocked(currentTime, entry, inputTargets);
1724}
1725
1726std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1727 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1728 std::vector<InputTarget> inputTargets;
1729 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001730 const sp<IBinder>& token = handle->getToken();
1731 if (token == nullptr) {
1732 continue;
1733 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001734 std::shared_ptr<Connection> connection = getConnectionLocked(token);
1735 if (connection == nullptr) {
1736 continue; // Connection has gone away
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001737 }
1738 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08001739 target.connection = connection;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001740 inputTargets.push_back(target);
1741 }
1742 return inputTargets;
1743}
1744
Prabir Pradhan24047542023-11-02 17:14:59 +00001745bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001746 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 if (!entry->dispatchInProgress) {
1749 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1750 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1751 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1752 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001753 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 // We have seen two identical key downs in a row which indicates that the device
1755 // driver is automatically generating key repeats itself. We take note of the
1756 // repeat here, but we disable our own next key repeat timer since it is clear that
1757 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001758 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1759 // Make sure we don't get key down from a different device. If a different
1760 // device Id has same key pressed down, the new device Id will replace the
1761 // current one to hold the key repeat with repeat count reset.
1762 // In the future when got a KEY_UP on the device id, drop it and do not
1763 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1765 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001766 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 } else {
1768 // Not a repeat. Save key down state in case we do see a repeat later.
1769 resetKeyRepeatLocked();
1770 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1771 }
1772 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001773 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1774 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001775 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001776 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1778 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001779 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 resetKeyRepeatLocked();
1781 }
1782
1783 if (entry->repeatCount == 1) {
1784 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1785 } else {
1786 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1787 }
1788
1789 entry->dispatchInProgress = true;
1790
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793
1794 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001795 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001797 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return false; // wait until next wakeup
1799 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001800 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 entry->interceptKeyWakeupTime = 0;
1802 }
1803
1804 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001805 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001807 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001808 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001809
1810 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1811 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1812 };
1813 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001814 // Poke user activity for keys not passed to user
1815 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 return false; // wait for the command to run
1817 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001818 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001820 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001821 if (*dropReason == DropReason::NOT_DROPPED) {
1822 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824 }
1825
1826 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001827 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001828 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001829 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1830 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001831 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001832 // Poke user activity for undispatched keys
1833 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 return true;
1835 }
1836
1837 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001838 InputEventInjectionResult injectionResult;
1839 sp<WindowInfoHandle> focusedWindow =
1840 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1841 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 return false;
1844 }
1845
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001846 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 return true;
1849 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001850 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1851
1852 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001853 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1854 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001856 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001857 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001859 if (mTracer) {
1860 ensureEventTraced(*entry);
1861 for (const auto& target : inputTargets) {
1862 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1863 }
1864 }
1865
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 // Dispatch the key.
1867 dispatchEventLocked(currentTime, entry, inputTargets);
1868 return true;
1869}
1870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001871void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001872 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1873 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1874 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1875 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1876 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1877 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1878 entry.metaState, entry.repeatCount, entry.downTime);
1879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880}
1881
Prabir Pradhancef936d2021-07-21 16:17:52 +00001882void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001883 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001884 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001885 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1886 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1887 "source=0x%x, sensorType=%s",
1888 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001889 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001890 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001891 auto command = [this, entry]() REQUIRES(mLock) {
1892 scoped_unlock unlock(mLock);
1893
1894 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001895 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001896 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001897 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1898 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001899 };
1900 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001901}
1902
1903bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001904 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1905 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001906 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001907 }
Chris Yef59a2f42020-10-16 12:55:26 -07001908 { // acquire lock
1909 std::scoped_lock _l(mLock);
1910
1911 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001912 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001913 if (entry->type == EventEntry::Type::SENSOR) {
1914 it = mInboundQueue.erase(it);
1915 releaseInboundEventLocked(entry);
1916 }
1917 }
1918 }
1919 return true;
1920}
1921
Prabir Pradhan24047542023-11-02 17:14:59 +00001922bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1923 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001924 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001927 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 entry->dispatchInProgress = true;
1929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932
1933 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001934 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001935 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1937 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 return true;
1939 }
1940
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001941 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942
1943 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001944 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001946 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 if (isPointerEvent) {
1948 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001949
1950 if (mDragState &&
1951 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1952 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1953 pilferPointersLocked(mDragState->dragWindow->getToken());
1954 }
1955
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001956 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001957 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001958 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1959 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 } else {
1961 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001962 sp<WindowInfoHandle> focusedWindow =
1963 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1964 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1965 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001966 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1967 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1968 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 return false;
1973 }
1974
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001975 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001976 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001977 return true;
1978 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001980 CancelationOptions::Mode mode(
1981 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1982 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001983 CancelationOptions options(mode, "input event injection failed");
Linnan Lid8150952024-01-26 18:07:17 +00001984 options.displayId = entry->displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001985 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 return true;
1987 }
1988
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001989 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001990 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001992 if (mTracer) {
1993 ensureEventTraced(*entry);
1994 for (const auto& target : inputTargets) {
1995 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1996 }
1997 }
1998
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 dispatchEventLocked(currentTime, entry, inputTargets);
2001 return true;
2002}
2003
chaviw98318de2021-05-19 16:45:23 -05002004void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00002005 bool isExiting, const int32_t rawX,
2006 const int32_t rawY) {
2007 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08002008 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002009 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2010 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002011
2012 enqueueInboundEventLocked(std::move(dragEntry));
2013}
2014
Prabir Pradhan24047542023-11-02 17:14:59 +00002015void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2016 std::shared_ptr<const DragEntry> entry) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002017 std::shared_ptr<Connection> connection = getConnectionLocked(entry->connectionToken);
2018 if (connection == nullptr) {
2019 return; // Connection has gone away
arthurhungb89ccb02020-12-30 16:19:01 +08002020 }
2021 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002022 target.connection = connection;
arthurhungb89ccb02020-12-30 16:19:01 +08002023 entry->dispatchInProgress = true;
2024 dispatchEventLocked(currentTime, entry, {target});
2025}
2026
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002027void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002028 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002029 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002030 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002031 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002032 "metaState=0x%x, buttonState=0x%x,"
2033 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002034 prefix, entry.eventTime, entry.deviceId,
2035 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2036 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2037 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2038 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002040 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002041 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002042 "x=%f, y=%f, pressure=%f, size=%f, "
2043 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2044 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002045 i, entry.pointerProperties[i].id,
2046 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002047 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2048 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2049 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2050 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2051 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2052 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2053 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2054 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2055 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058}
2059
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002060void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002061 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002064 if (DEBUG_DISPATCH_CYCLE) {
2065 ALOGD("dispatchEventToCurrentInputTargets");
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002068 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002069
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2071
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002072 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002074 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002075 std::shared_ptr<Connection> connection = inputTarget.connection;
2076 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
2078}
2079
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002080void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002081 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2082 // If the policy decides to close the app, we will get a channel removal event via
2083 // unregisterInputChannel, and will clean up the connection that way. We are already not
2084 // sending new pointers to the connection when it blocked, but focused events will continue to
2085 // pile up.
2086 ALOGW("Canceling events for %s because it is unresponsive",
2087 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002088 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002089 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 "application not responding");
2091 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
2093}
2094
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002096 if (DEBUG_FOCUS) {
2097 ALOGD("Resetting ANR timeouts.");
2098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
2100 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002102 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103}
2104
Tiger Huang721e26f2018-07-24 22:26:19 +08002105/**
2106 * Get the display id that the given event should go to. If this event specifies a valid display id,
2107 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2108 * Focused display is the display that the user most recently interacted with.
2109 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002110int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002111 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002112 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002113 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002114 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2115 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002116 break;
2117 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002118 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2120 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 break;
2122 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002123 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002124 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002125 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002126 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002127 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002128 case EventEntry::Type::SENSOR:
2129 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002130 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 return ADISPLAY_ID_NONE;
2132 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002133 }
2134 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2135}
2136
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002137bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2138 const char* focusedWindowName) {
2139 if (mAnrTracker.empty()) {
2140 // already processed all events that we waited for
2141 mKeyIsWaitingForEventsTimeout = std::nullopt;
2142 return false;
2143 }
2144
2145 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2146 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002147 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002148 mKeyIsWaitingForEventsTimeout = currentTime +
2149 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2150 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 return true;
2152 }
2153
2154 // We still have pending events, and already started the timer
2155 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2156 return true; // Still waiting
2157 }
2158
2159 // Waited too long, and some connection still hasn't processed all motions
2160 // Just send the key to the focused window
2161 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2162 focusedWindowName);
2163 mKeyIsWaitingForEventsTimeout = std::nullopt;
2164 return false;
2165}
2166
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002167sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002168 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002169 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002170 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
Tiger Huang721e26f2018-07-24 22:26:19 +08002172 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002173 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002174 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002175 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2176
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 // If there is no currently focused window and no focused application
2178 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2180 ALOGI("Dropping %s event because there is no focused window or focused application in "
2181 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185
Vishnu Nair062a8672021-09-03 16:07:44 -07002186 // Drop key events if requested by input feature
2187 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002189 }
2190
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2192 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2193 // start interacting with another application via touch (app switch). This code can be removed
2194 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2195 // an app is expected to have a focused window.
2196 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2197 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2198 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002199 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2200 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2201 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002202 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002203 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002204 ALOGW("Waiting because no window has focus but %s may eventually add a "
2205 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002206 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002207 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002208 outInjectionResult = InputEventInjectionResult::PENDING;
2209 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2211 // Already raised ANR. Drop the event
2212 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002213 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002214 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002215 } else {
2216 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217 outInjectionResult = InputEventInjectionResult::PENDING;
2218 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002219 }
2220 }
2221
2222 // we have a valid, non-null focused window
2223 resetNoFocusedWindowTimeoutLocked();
2224
Prabir Pradhan5735a322022-04-11 17:23:34 +00002225 // Verify targeted injection.
2226 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2227 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002228 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2229 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002232 if (focusedWindowHandle->getInfo()->inputConfig.test(
2233 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::PENDING;
2236 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 }
2238
2239 // If the event is a key event, then we must wait for all previous events to
2240 // complete before delivering it because previous events may have the
2241 // side-effect of transferring focus to a different window and we want to
2242 // ensure that the following keys are sent to the new window.
2243 //
2244 // Suppose the user touches a button in a window then immediately presses "A".
2245 // If the button causes a pop-up window to appear then we want to ensure that
2246 // the "A" key is delivered to the new pop-up window. This is because users
2247 // often anticipate pending UI changes when typing on a keyboard.
2248 // To obtain this behavior, we must serialize key events with respect to all
2249 // prior input events.
2250 if (entry.type == EventEntry::Type::KEY) {
2251 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002252 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = InputEventInjectionResult::PENDING;
2254 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 }
2257
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002258 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2259 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260}
2261
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262/**
2263 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2264 * that are currently unresponsive.
2265 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002266std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2267 const std::vector<Monitor>& monitors) const {
2268 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002270 [](const Monitor& monitor) REQUIRES(mLock) {
2271 std::shared_ptr<Connection> connection = monitor.connection;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002272 if (!connection->responsive) {
2273 ALOGW("Unresponsive monitor %s will not get the new gesture",
2274 connection->inputChannel->getName().c_str());
2275 return false;
2276 }
2277 return true;
2278 });
2279 return responsiveMonitors;
2280}
2281
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002282std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002283 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002284 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002285 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002287 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // For security reasons, we defer updating the touch state until we are sure that
2289 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290 const int32_t displayId = entry.displayId;
2291 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002292 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293
2294 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002295 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002297 // Copy current touch state into tempTouchState.
2298 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2299 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002300 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002301 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2303 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002304 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002305 }
2306
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002307 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308
2309 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2310 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2311 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002312 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2313 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002314 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002315 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2316 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002317 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2318 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2319 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002320 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002321
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002322 if (newGesture) {
2323 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002324 }
2325
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002326 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2327 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2328 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002331 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002332 if (wasDown) {
2333 // Started hovering, but the device is already down: reject the hover event
2334 LOG(ERROR) << "Got hover event " << entry.getDescription()
2335 << " but the device is already down " << oldState->dump();
2336 outInjectionResult = InputEventInjectionResult::FAILED;
2337 return {};
2338 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002339 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2340 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002341 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002342 }
2343
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2345 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002346 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002347 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002348 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002349 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2350 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002351 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002352 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002353 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002354
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002355 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002356 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002359 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002360 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002362 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002363 }
2364
Prabir Pradhan5735a322022-04-11 17:23:34 +00002365 // Verify targeted injection.
2366 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2367 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002369 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002370 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002371 }
2372
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002373 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002374 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002375 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2376 // New window supports splitting, but we should never split mouse events.
2377 isSplit = !isFromMouse;
2378 } else if (isSplit) {
2379 // New window does not support splitting but we have already split events.
2380 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002381 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2382 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002383 newTouchedWindowHandle = nullptr;
2384 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002385 } else {
2386 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002387 // be delivered to a new window which supports split touch. Pointers from a mouse device
2388 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002389 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002390 }
2391
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002392 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002393 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002394 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002395 // Process the foreground window first so that it is the first to receive the event.
2396 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 }
2398
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002399 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002400 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2401 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002402 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002403 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002404 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002405 }
2406
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002407 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002408 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002409 continue;
2410 }
2411
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002412 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002413 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002414 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002415 }
2416
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002417 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002418 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002419
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002420 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2421 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002423 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424
2425 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002426 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002427 }
2428 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002429 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002431 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002432 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002433
2434 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002435
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002436 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002437 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2438 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002439 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002440 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002441 isDownOrPointerDown
2442 ? std::make_optional(entry.eventTime)
2443 : std::nullopt);
2444 // If this is the pointer going down and the touched window has a wallpaper
2445 // then also add the touched wallpaper windows so they are locked in for the
2446 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2447 // SCROLL because the wallpaper engine only supports touch events. We would need to
2448 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2449 // handle these events.
2450 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002451 windowHandle->getInfo()->inputConfig.test(
2452 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2453 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2454 if (wallpaper != nullptr) {
2455 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2456 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002457 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002458 if (isSplit) {
2459 wallpaperFlags |= InputTarget::Flags::SPLIT;
2460 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002461 tempTouchState.addOrUpdateWindow(wallpaper,
2462 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002463 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002464 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002465 }
2466 }
2467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002469
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002470 // If a window is already pilfering some pointers, give it this new pointer as well and
2471 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2472 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002473 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002474 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002475 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002476 // This window is already pilfering some pointers, and this new pointer is also
2477 // going to it. Therefore, take over this pointer and don't give it to anyone
2478 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002479 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002480 }
2481 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002482
2483 // Restrict all pilfered pointers to the pilfering windows.
2484 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 } else {
2486 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2487
2488 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002489 if (!tempTouchState.isDown(entry.deviceId) &&
2490 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002491 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2492 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2493 << " is not down or we previously dropped the pointer down event in "
2494 << "display " << displayId << ": " << entry.getDescription();
2495 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
2499
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002500 // If the pointer is not currently hovering, then ignore the event.
2501 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2502 const int32_t pointerId = entry.pointerProperties[0].id;
2503 if (oldState == nullptr ||
2504 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2505 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2506 "display "
2507 << displayId << ": " << entry.getDescription();
2508 outInjectionResult = InputEventInjectionResult::FAILED;
2509 return {};
2510 }
2511 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2512 }
2513
arthurhung6d4bed92021-03-17 11:59:33 +08002514 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002515
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002517 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002518 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002519 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002520 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002521 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002522 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002523 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002524 sp<WindowInfoHandle> newTouchedWindowHandle =
2525 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002526
Prabir Pradhan5735a322022-04-11 17:23:34 +00002527 // Verify targeted injection.
2528 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2529 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002530 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002531 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002532 }
2533
Vishnu Nair062a8672021-09-03 16:07:44 -07002534 // Drop touch events if requested by input feature
2535 if (newTouchedWindowHandle != nullptr &&
2536 shouldDropInput(entry, newTouchedWindowHandle)) {
2537 newTouchedWindowHandle = nullptr;
2538 }
2539
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002540 if (newTouchedWindowHandle != nullptr &&
2541 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002542 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002543 oldTouchedWindowHandle->getName().c_str(),
2544 newTouchedWindowHandle->getName().c_str(), displayId);
2545
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002547 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002548 const PointerProperties& pointer = entry.pointerProperties[0];
2549 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002550
2551 const TouchedWindow& touchedWindow =
2552 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002553 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002554 InputTarget::DispatchMode::SLIPPERY_EXIT,
2555 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002556 touchedWindow.getDownTimeInTarget(entry.deviceId),
2557 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558
2559 // Make a slippery entrance into the new window.
2560 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002561 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002564 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002565 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002566 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002572 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002573 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002574 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 }
2576
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002577 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2578 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002579 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002580 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002581
2582 // Check if the wallpaper window should deliver the corresponding event.
2583 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002584 tempTouchState, entry.deviceId, pointer, targets);
2585 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002586 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588 }
Arthur Hung96483742022-11-15 03:30:48 +00002589
2590 // Update the pointerIds for non-splittable when it received pointer down.
2591 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2592 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002593 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002594 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2595 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002596 // Ignore drag window for it should just track one pointer.
2597 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2598 continue;
2599 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002600 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002601 }
2602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002605 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002606 {
2607 std::vector<TouchedWindow> hoveringWindows =
2608 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2609 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002610 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002611 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2612 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002613 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002614 if (!target) {
2615 continue;
2616 }
2617 // Hardcode to single hovering pointer for now.
2618 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2619 pointerIds.set(entry.pointerProperties[0].id);
2620 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2621 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624
Prabir Pradhan5735a322022-04-11 17:23:34 +00002625 // Ensure that all touched windows are valid for injection.
2626 if (entry.injectionState != nullptr) {
2627 std::string errs;
2628 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002629 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2630 if (err) errs += "\n - " + *err;
2631 }
2632 if (!errs.empty()) {
2633 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002634 "%s:%s",
2635 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002636 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002637 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002638 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002639 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002640
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002641 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2642 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002644 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002645 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002646 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002647 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002648 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002649 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002650 sp<WindowInfoHandle> targetWindow =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002651 getWindowHandleLocked(target.connection->getToken());
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002652 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2653 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
2656 }
2657 }
2658 }
2659
Harry Cuttsb166c002023-05-09 13:06:05 +00002660 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2661 // only want the system UI to handle these gestures.
2662 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2663 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2664 if (isTouchpadNavGesture) {
2665 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2666 }
2667
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002668 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002669 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002670 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002671 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002672 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002673 continue;
2674 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002675 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002676 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002677 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002678 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002679
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002680 // During targeted injection, only allow owned targets to receive events
2681 std::erase_if(targets, [&](const InputTarget& target) {
2682 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2683 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2684 if (err) {
2685 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2686 << ": " << (*err);
2687 return true;
2688 }
2689 return false;
2690 });
2691
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002692 if (targets.empty()) {
2693 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2694 outInjectionResult = InputEventInjectionResult::FAILED;
2695 return {};
2696 }
2697
2698 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2699 // window that is actually receiving the entire gesture.
2700 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002701 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002702 })) {
2703 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2704 << entry.getDescription();
2705 outInjectionResult = InputEventInjectionResult::FAILED;
2706 return {};
2707 }
2708
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002709 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Prabir Pradhan502a7252023-12-01 16:11:24 +00002711 // Now that we have generated all of the input targets for this event, reset the dispatch
2712 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002713 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002714 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002715 }
2716
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002717 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002718 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002719 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002720 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002721 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002722 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002723 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002724 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2725 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002726 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2727 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2728 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 }
2730
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 // Save changes unless the action was scroll in which case the temporary touch
2732 // state was only valid for this one action.
2733 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002734 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002735 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002736 mTouchStatesByDisplay[displayId] = tempTouchState;
2737 } else {
2738 mTouchStatesByDisplay.erase(displayId);
2739 }
2740 }
2741
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002742 if (tempTouchState.windows.empty()) {
2743 mTouchStatesByDisplay.erase(displayId);
2744 }
2745
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002746 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747}
2748
arthurhung6d4bed92021-03-17 11:59:33 +08002749void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002750 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2751 // have an explicit reason to support it.
2752 constexpr bool isStylus = false;
2753
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002754 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002755 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002756 if (dropWindow) {
2757 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002758 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002759 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002760 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002761 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002762 }
2763 mDragState.reset();
2764}
2765
2766void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002767 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002768 return;
2769 }
2770
arthurhung6d4bed92021-03-17 11:59:33 +08002771 if (!mDragState->isStartDrag) {
2772 mDragState->isStartDrag = true;
2773 mDragState->isStylusButtonDownAtStart =
2774 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2775 }
2776
Arthur Hung54745652022-04-20 07:17:41 +00002777 // Find the pointer index by id.
2778 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002779 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002780 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2781 if (pointerProperties.id == mDragState->pointerId) {
2782 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002783 }
Arthur Hung54745652022-04-20 07:17:41 +00002784 }
arthurhung6d4bed92021-03-17 11:59:33 +08002785
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002786 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002787 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002788 }
2789
2790 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2791 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2792 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2793
2794 switch (maskedAction) {
2795 case AMOTION_EVENT_ACTION_MOVE: {
2796 // Handle the special case : stylus button no longer pressed.
2797 bool isStylusButtonDown =
2798 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2799 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2800 finishDragAndDrop(entry.displayId, x, y);
2801 return;
2802 }
2803
2804 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2805 // until we have an explicit reason to support it.
2806 constexpr bool isStylus = false;
2807
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002808 sp<WindowInfoHandle> hoverWindowHandle =
2809 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2810 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002811 // enqueue drag exit if needed.
2812 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2813 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2814 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002815 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002816 y);
2817 }
2818 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2819 }
2820 // enqueue drag location if needed.
2821 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002822 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002823 }
2824 break;
2825 }
2826
2827 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002828 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002829 break;
2830 }
2831 // The drag pointer is up.
2832 [[fallthrough]];
2833 case AMOTION_EVENT_ACTION_UP:
2834 finishDragAndDrop(entry.displayId, x, y);
2835 break;
2836 case AMOTION_EVENT_ACTION_CANCEL: {
2837 ALOGD("Receiving cancel when drag and drop.");
2838 sendDropWindowCommandLocked(nullptr, 0, 0);
2839 mDragState.reset();
2840 break;
2841 }
arthurhungb89ccb02020-12-30 16:19:01 +08002842 }
2843}
2844
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002845std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2846 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002847 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002848 std::optional<nsecs_t> firstDownTimeInTarget) const {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002849 std::shared_ptr<Connection> connection = getConnectionLocked(windowHandle->getToken());
2850 if (connection == nullptr) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002851 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2852 return {};
2853 }
2854 InputTarget inputTarget;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002855 inputTarget.connection = connection;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002856 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002857 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002858 inputTarget.flags = targetFlags;
2859 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2860 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2861 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2862 if (displayInfoIt != mDisplayInfos.end()) {
2863 inputTarget.displayTransform = displayInfoIt->second.transform;
2864 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002865 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002866 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2867 }
2868 return inputTarget;
2869}
2870
chaviw98318de2021-05-19 16:45:23 -05002871void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002872 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002873 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002874 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002875 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002876 std::vector<InputTarget>::iterator it =
2877 std::find_if(inputTargets.begin(), inputTargets.end(),
2878 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002879 return inputTarget.connection->getToken() == windowHandle->getToken();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002880 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002881
chaviw98318de2021-05-19 16:45:23 -05002882 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002883
2884 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002885 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002886 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2887 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002888 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002889 return;
2890 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002891 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002892 it = inputTargets.end() - 1;
2893 }
2894
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002895 if (it->flags != targetFlags) {
2896 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2897 }
2898 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2899 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2900 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2901 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002902}
2903
2904void InputDispatcher::addPointerWindowTargetLocked(
2905 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002906 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2907 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2908 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002909 if (pointerIds.none()) {
2910 for (const auto& target : inputTargets) {
2911 LOG(INFO) << "Target: " << target;
2912 }
2913 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2914 return;
2915 }
2916 std::vector<InputTarget>::iterator it =
2917 std::find_if(inputTargets.begin(), inputTargets.end(),
2918 [&windowHandle](const InputTarget& inputTarget) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002919 return inputTarget.connection->getToken() == windowHandle->getToken();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002920 });
2921
2922 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2923 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2924 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2925 // input targets for hovering pointers and for touching pointers.
2926 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2927 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002928 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002929 // Force the code below to create a new input target
2930 it = inputTargets.end();
2931 }
2932
2933 const WindowInfo* windowInfo = windowHandle->getInfo();
2934
2935 if (it == inputTargets.end()) {
2936 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002937 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2938 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002939 if (!target) {
2940 return;
2941 }
2942 inputTargets.push_back(*target);
2943 it = inputTargets.end() - 1;
2944 }
2945
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002946 if (it->dispatchMode != dispatchMode) {
2947 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2948 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2949 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002950 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002951 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2952 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002953 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002954 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002955 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002956 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2957 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002958
chaviw1ff3d1e2020-07-01 15:53:47 -07002959 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960}
2961
Michael Wright3dd60e22019-03-27 22:06:44 +00002962void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002963 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002964 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2965 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002966
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002967 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2968 InputTarget target;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08002969 target.connection = monitor.connection;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002970 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2971 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002972 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2973 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002974 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002975 target.setDefaultPointerTransform(target.displayTransform);
2976 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
2978}
2979
Robert Carrc9bf1d32020-04-13 17:21:08 -07002980/**
2981 * Indicate whether one window handle should be considered as obscuring
2982 * another window handle. We only check a few preconditions. Actually
2983 * checking the bounds is left to the caller.
2984 */
chaviw98318de2021-05-19 16:45:23 -05002985static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2986 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002987 // Compare by token so cloned layers aren't counted
2988 if (haveSameToken(windowHandle, otherHandle)) {
2989 return false;
2990 }
2991 auto info = windowHandle->getInfo();
2992 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002993 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002994 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002995 } else if (otherInfo->alpha == 0 &&
2996 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002997 // Those act as if they were invisible, so we don't need to flag them.
2998 // We do want to potentially flag touchable windows even if they have 0
2999 // opacity, since they can consume touches and alter the effects of the
3000 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003001 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003002 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3003 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003004 } else if (info->ownerUid == otherInfo->ownerUid) {
3005 // If ownerUid is the same we don't generate occlusion events as there
3006 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003007 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003008 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003009 return false;
3010 } else if (otherInfo->displayId != info->displayId) {
3011 return false;
3012 }
3013 return true;
3014}
3015
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003016/**
3017 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3018 * untrusted, one should check:
3019 *
3020 * 1. If result.hasBlockingOcclusion is true.
3021 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3022 * BLOCK_UNTRUSTED.
3023 *
3024 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3025 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3026 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3027 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3028 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3029 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3030 *
3031 * If neither of those is true, then it means the touch can be allowed.
3032 */
3033InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003034 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3035 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003036 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003037 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003038 TouchOcclusionInfo info;
3039 info.hasBlockingOcclusion = false;
3040 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003041 info.obscuringUid = gui::Uid::INVALID;
3042 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003043 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003044 if (windowHandle == otherHandle) {
3045 break; // All future windows are below us. Exit early.
3046 }
chaviw98318de2021-05-19 16:45:23 -05003047 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003048 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3049 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003050 if (DEBUG_TOUCH_OCCLUSION) {
3051 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003052 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003053 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003054 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3055 // we perform the checks below to see if the touch can be propagated or not based on the
3056 // window's touch occlusion mode
3057 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3058 info.hasBlockingOcclusion = true;
3059 info.obscuringUid = otherInfo->ownerUid;
3060 info.obscuringPackage = otherInfo->packageName;
3061 break;
3062 }
3063 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003064 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003065 float opacity =
3066 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3067 // Given windows A and B:
3068 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3069 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3070 opacityByUid[uid] = opacity;
3071 if (opacity > info.obscuringOpacity) {
3072 info.obscuringOpacity = opacity;
3073 info.obscuringUid = uid;
3074 info.obscuringPackage = otherInfo->packageName;
3075 }
3076 }
3077 }
3078 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003079 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003080 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003081 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082 return info;
3083}
3084
chaviw98318de2021-05-19 16:45:23 -05003085std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003086 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003087 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003088 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3089 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3090 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003091 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003092 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003093 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3094 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003095 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3096 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3097 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003098 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003099}
3100
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003101bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3102 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003103 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3104 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003105 return false;
3106 }
3107 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003108 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003109 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003110 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003111 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3112 return false;
3113 }
3114 return true;
3115}
3116
chaviw98318de2021-05-19 16:45:23 -05003117bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003120 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3121 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003122 if (windowHandle == otherHandle) {
3123 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
chaviw98318de2021-05-19 16:45:23 -05003125 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003126 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003127 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 return true;
3129 }
3130 }
3131 return false;
3132}
3133
chaviw98318de2021-05-19 16:45:23 -05003134bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003135 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003136 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3137 const WindowInfo* windowInfo = windowHandle->getInfo();
3138 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003139 if (windowHandle == otherHandle) {
3140 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003141 }
chaviw98318de2021-05-19 16:45:23 -05003142 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003143 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003144 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003145 return true;
3146 }
3147 }
3148 return false;
3149}
3150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003151std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003152 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003153 if (applicationHandle != nullptr) {
3154 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003155 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 } else {
3157 return applicationHandle->getName();
3158 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003159 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003160 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003162 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
3164}
3165
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003166void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003167 if (!isUserActivityEvent(eventEntry)) {
3168 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003169 return;
3170 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003171
3172 const int32_t eventType = getUserActivityEventType(eventEntry);
3173 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3174 // Note that we're directly getting the time diff between the current event and the previous
3175 // event. This is assuming that the first user event always happens at a timestamp that is
3176 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3177 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3178 // value than the potential first user activity event time, so this is ok.
3179 std::chrono::nanoseconds timeSinceLastEvent =
3180 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3181 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3182 return;
3183 }
3184 }
3185
Tiger Huang721e26f2018-07-24 22:26:19 +08003186 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003187 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003188 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003189 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003190 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003191 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003192 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 }
3194 }
3195
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003196 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003197 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003198 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3199 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 return;
3201 }
Josep del Riob3981622023-04-18 15:49:45 +00003202 if (windowDisablingUserActivityInfo != nullptr) {
3203 if (DEBUG_DISPATCH_CYCLE) {
3204 ALOGD("Not poking user activity: disabled by window '%s'.",
3205 windowDisablingUserActivityInfo->name.c_str());
3206 }
3207 return;
3208 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003211 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003212 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3213 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 return;
3215 }
Josep del Riob3981622023-04-18 15:49:45 +00003216 // If the key code is unknown, we don't consider it user activity
3217 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3218 return;
3219 }
3220 // Don't inhibit events that were intercepted or are not passed to
3221 // the apps, like system shortcuts
3222 if (windowDisablingUserActivityInfo != nullptr &&
3223 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3224 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3225 if (DEBUG_DISPATCH_CYCLE) {
3226 ALOGD("Not poking user activity: disabled by window '%s'.",
3227 windowDisablingUserActivityInfo->name.c_str());
3228 }
3229 return;
3230 }
3231
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003234 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003235 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003236 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003237 break;
3238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 }
3240
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003241 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003242 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3243 REQUIRES(mLock) {
3244 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003245 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003246 };
3247 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248}
3249
3250void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003251 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003252 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003253 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003254 ATRACE_NAME_IF(ATRACE_ENABLED(),
3255 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3256 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003257 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003258 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003259 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003260 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003261 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003262 inputTarget.getPointerInfoString().c_str());
3263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264
3265 // Skip this event if the connection status is not normal.
3266 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003267 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003268 if (DEBUG_DISPATCH_CYCLE) {
3269 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003270 connection->getInputChannelName().c_str(),
3271 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 return;
3274 }
3275
3276 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003278 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003280 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003282 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003283 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003284 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3285 logDispatchStateLocked();
3286 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3287 "target on connection "
3288 << connection->getInputChannelName() << " for "
3289 << originalMotionEntry.getDescription();
3290 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003292 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3293 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 if (!splitMotionEntry) {
3295 return; // split event was dropped
3296 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003297 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3298 std::string reason = std::string("reason=pointer cancel on split window");
3299 android_log_event_list(LOGTAG_INPUT_CANCEL)
3300 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3301 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003302 if (DEBUG_FOCUS) {
3303 ALOGD("channel '%s' ~ Split motion event.",
3304 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003305 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003306 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003307 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3308 std::move(splitMotionEntry),
3309 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 return;
3311 }
3312 }
3313
3314 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003315 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3316 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317}
3318
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003319void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3320 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3321 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003322 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003323 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3324 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003325 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003326
hongzuo liu95785e22022-09-06 02:51:35 +00003327 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003329 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003332 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 startDispatchCycleLocked(currentTime, connection);
3334 }
3335}
3336
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003337void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003338 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003339 const InputTarget& inputTarget) {
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003340 // TODO(b/210460522): Verify all targets excluding global monitors are associated with a window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 // This is a new event.
3342 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003343 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003344 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003346 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3347 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003348 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003350 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003351 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003352 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3353 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003354 LOG(WARNING) << "channel " << connection->getInputChannelName()
3355 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 return; // skip the inconsistent event
3357 }
3358 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003361 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003362 std::shared_ptr<const MotionEntry> resolvedMotion =
3363 std::static_pointer_cast<const MotionEntry>(eventEntry);
3364 {
3365 // Determine the resolved motion entry.
3366 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3367 int32_t resolvedAction = motionEntry.action;
3368 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003370 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003371 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003372 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003373 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003374 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003375 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003376 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003377 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003378 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003379 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3380 }
3381 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3382 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3383 motionEntry.displayId)) {
3384 if (DEBUG_DISPATCH_CYCLE) {
3385 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3386 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3387 "enter event";
3388 }
3389 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3390 }
3391
3392 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3393 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3394 }
3395 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3396 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3397 }
3398 if (dispatchEntry->targetFlags.test(
3399 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3400 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3401 }
3402
3403 dispatchEntry->resolvedFlags = resolvedFlags;
3404 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003405 std::optional<std::vector<PointerProperties>> usingProperties;
3406 std::optional<std::vector<PointerCoords>> usingCoords;
3407 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3408 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3409 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3410 // the dispatcher, and therefore the coordinates of this event are currently
3411 // incorrect. These events should use the coordinates of the last dispatched
3412 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3413 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3414 std::optional<std::pair<std::vector<PointerProperties>,
3415 std::vector<PointerCoords>>>
3416 pointerInfo =
3417 connection->inputState.getPointersOfLastEvent(motionEntry,
3418 hovering);
3419 if (pointerInfo) {
3420 usingProperties = pointerInfo->first;
3421 usingCoords = pointerInfo->second;
3422 }
3423 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003424 // Generate a new MotionEntry with a new eventId using the resolved action and
3425 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003426 resolvedMotion = std::make_shared<
3427 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3428 motionEntry.eventTime, motionEntry.deviceId,
3429 motionEntry.source, motionEntry.displayId,
3430 motionEntry.policyFlags, resolvedAction,
3431 motionEntry.actionButton, resolvedFlags,
3432 motionEntry.metaState, motionEntry.buttonState,
3433 motionEntry.classification, motionEntry.edgeFlags,
3434 motionEntry.xPrecision, motionEntry.yPrecision,
3435 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3436 motionEntry.downTime,
3437 usingProperties.value_or(motionEntry.pointerProperties),
3438 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003439 if (ATRACE_ENABLED()) {
3440 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3441 ") to MotionEvent(id=0x%" PRIx32 ").",
3442 motionEntry.id, resolvedMotion->id);
3443 ATRACE_NAME(message.c_str());
3444 }
3445
3446 // Set the resolved motion entry in the DispatchEntry.
3447 dispatchEntry->eventEntry = resolvedMotion;
3448 eventEntry = resolvedMotion;
3449 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003452 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3453 // devices being active at the same time in the same window, so if a new device is
3454 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003455 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003456 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003457 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003458 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003459 << connection->getInputChannelName() << " with event "
3460 << cancelEvent->getDescription();
3461 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3462 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003463 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003464
3465 // Send these cancel events to the queue before sending the event from the new
3466 // device.
3467 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3468 }
3469
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003470 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003472 LOG(WARNING) << "channel " << connection->getInputChannelName()
3473 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003474 return; // skip the inconsistent event
3475 }
3476
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003477 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3478 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003479 // Skip reporting pointer down outside focus to the policy.
3480 break;
3481 }
3482
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003483 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003484 inputTarget.connection->getToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485
3486 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003488 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003489 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003490 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3491 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003492 break;
3493 }
Chris Yef59a2f42020-10-16 12:55:26 -07003494 case EventEntry::Type::SENSOR: {
3495 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3496 break;
3497 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003498 case EventEntry::Type::CONFIGURATION_CHANGED:
3499 case EventEntry::Type::DEVICE_RESET: {
3500 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003501 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003502 break;
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
3505
3506 // Remember that we are waiting for this dispatch to complete.
3507 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003508 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 }
3510
3511 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003512 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003513 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003514}
3515
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003516/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003517 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003518 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003519 * The first role is to log input interaction with windows, which helps determine what the user was
3520 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3521 * that user started interacting with launcher window, as well as any other window that received
3522 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3523 * when the set of tokens that received the event changes. It is not logged again as long as the
3524 * user is interacting with the same windows.
3525 *
3526 * The second role is to track input device activity for metrics collection. For each input event,
3527 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3528 * input_interaction logs, the device interaction is reported even when the set of interaction
3529 * tokens do not change.
3530 *
3531 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3532 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003533 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003534void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3535 const std::vector<InputTarget>& targets) {
3536 int32_t deviceId;
3537 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003538 // Skip ACTION_UP events, and all events other than keys and motions
3539 if (entry.type == EventEntry::Type::KEY) {
3540 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3541 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3542 return;
3543 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003544 deviceId = keyEntry.deviceId;
3545 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003546 } else if (entry.type == EventEntry::Type::MOTION) {
3547 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3548 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003549 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3550 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003551 return;
3552 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003553 deviceId = motionEntry.deviceId;
3554 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003555 } else {
3556 return; // Not a key or a motion
3557 }
3558
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003559 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003560 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003561 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003562 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003563 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003564 continue; // Skip windows that receive ACTION_OUTSIDE
3565 }
3566
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003567 sp<IBinder> token = target.connection->getToken();
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003568 newConnectionTokens.insert(std::move(token));
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003569 newConnections.emplace_back(target.connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003570 if (target.windowHandle) {
3571 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3572 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003573 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003574
3575 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3576 REQUIRES(mLock) {
3577 scoped_unlock unlock(mLock);
3578 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3579 };
3580 postCommandLocked(std::move(command));
3581
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003582 if (newConnectionTokens == mInteractionConnectionTokens) {
3583 return; // no change
3584 }
3585 mInteractionConnectionTokens = newConnectionTokens;
3586
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003587 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003588 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003589 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003590 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003591 std::string message = "Interaction with: " + targetList;
3592 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 message += "<none>";
3594 }
3595 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3596}
3597
chaviwfd6d3512019-03-25 13:23:49 -07003598void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003599 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003600 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003601 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3602 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003603 return;
3604 }
3605
Vishnu Nairc519ff72021-01-21 08:23:08 -08003606 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003607 if (focusedToken == token) {
3608 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003609 return;
3610 }
3611
Prabir Pradhancef936d2021-07-21 16:17:52 +00003612 auto command = [this, token]() REQUIRES(mLock) {
3613 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003614 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003615 };
3616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003619status_t InputDispatcher::publishMotionEvent(Connection& connection,
3620 DispatchEntry& dispatchEntry) const {
3621 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3622 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3623
3624 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003625 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003626
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003627 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003628 // Set the X and Y offset and X and Y scale depending on the input source.
3629 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003630 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003631 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3632 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003633 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003634 scaledCoords[i] = motionEntry.pointerCoords[i];
3635 // Don't apply window scale here since we don't want scale to affect raw
3636 // coordinates. The scale will be sent back to the client and applied
3637 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003638 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003639 }
3640 usingCoords = scaledCoords;
3641 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003642 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003643 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003644 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003645 scaledCoords[i].clear();
3646 }
3647 usingCoords = scaledCoords;
3648 }
3649
3650 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3651
3652 // Publish the motion event.
3653 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003654 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3655 motionEntry.source, motionEntry.displayId, std::move(hmac),
3656 motionEntry.action, motionEntry.actionButton,
3657 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3658 motionEntry.metaState, motionEntry.buttonState,
3659 motionEntry.classification, dispatchEntry.transform,
3660 motionEntry.xPrecision, motionEntry.yPrecision,
3661 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3662 dispatchEntry.rawTransform, motionEntry.downTime,
3663 motionEntry.eventTime, motionEntry.getPointerCount(),
3664 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003665}
3666
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003668 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003669 ATRACE_NAME_IF(ATRACE_ENABLED(),
3670 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3671 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003672 if (DEBUG_DISPATCH_CYCLE) {
3673 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003676 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003677 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003679 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003680 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
3682 // Publish the event.
3683 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3685 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003686 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3688 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003689 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003690 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3691 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003694 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003695 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003696 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3697 keyEntry.deviceId, keyEntry.source,
3698 keyEntry.displayId, std::move(hmac),
3699 keyEntry.action, dispatchEntry->resolvedFlags,
3700 keyEntry.keyCode, keyEntry.scanCode,
3701 keyEntry.metaState, keyEntry.repeatCount,
3702 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003703 if (mTracer) {
3704 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3705 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003709 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003711 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3712 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003713 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003714 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003715 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003716 if (mTracer) {
3717 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3718 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 break;
3720 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003721
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003722 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003723 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003724 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003726 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003727 break;
3728 }
3729
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003730 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3731 const TouchModeEntry& touchModeEntry =
3732 static_cast<const TouchModeEntry&>(eventEntry);
3733 status = connection->inputPublisher
3734 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3735 touchModeEntry.inTouchMode);
3736
3737 break;
3738 }
3739
Prabir Pradhan99987712020-11-10 18:43:05 -08003740 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3741 const auto& captureEntry =
3742 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3743 status = connection->inputPublisher
3744 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003745 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003746 break;
3747 }
3748
arthurhungb89ccb02020-12-30 16:19:01 +08003749 case EventEntry::Type::DRAG: {
3750 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3751 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3752 dragEntry.id, dragEntry.x,
3753 dragEntry.y,
3754 dragEntry.isExiting);
3755 break;
3756 }
3757
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003758 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003759 case EventEntry::Type::DEVICE_RESET:
3760 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003761 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003762 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
3766
3767 // Check the result.
3768 if (status) {
3769 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003770 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003772 "This is unexpected because the wait queue is empty, so the pipe "
3773 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003774 "event to it, status=%s(%d)",
3775 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3776 status);
Harry Cutts33476232023-01-30 19:57:29 +00003777 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 } else {
3779 // Pipe is full and we are waiting for the app to finish process some events
3780 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 if (DEBUG_DISPATCH_CYCLE) {
3782 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3783 "waiting for the application to catch up",
3784 connection->getInputChannelName().c_str());
3785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787 } else {
3788 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003789 "status=%s(%d)",
3790 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3791 status);
Harry Cutts33476232023-01-30 19:57:29 +00003792 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794 return;
3795 }
3796
3797 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003798 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3799 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3800 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003801 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003802 if (connection->responsive) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003803 mAnrTracker.insert(timeoutTime, connection->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003804 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003805 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807}
3808
chaviw09c8d2d2020-08-24 15:48:26 -07003809std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3810 size_t size;
3811 switch (event.type) {
3812 case VerifiedInputEvent::Type::KEY: {
3813 size = sizeof(VerifiedKeyEvent);
3814 break;
3815 }
3816 case VerifiedInputEvent::Type::MOTION: {
3817 size = sizeof(VerifiedMotionEvent);
3818 break;
3819 }
3820 }
3821 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3822 return mHmacKeyManager.sign(start, size);
3823}
3824
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003825const std::array<uint8_t, 32> InputDispatcher::getSignature(
3826 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003827 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003828 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003829 // Only sign events up and down events as the purely move events
3830 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003831 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003832 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003833
3834 VerifiedMotionEvent verifiedEvent =
3835 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3836 verifiedEvent.actionMasked = actionMasked;
3837 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3838 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003839}
3840
3841const std::array<uint8_t, 32> InputDispatcher::getSignature(
3842 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3843 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3844 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003845 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003846}
3847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003849 const std::shared_ptr<Connection>& connection,
3850 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003851 if (DEBUG_DISPATCH_CYCLE) {
3852 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3853 connection->getInputChannelName().c_str(), seq, toString(handled));
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003856 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 return;
3858 }
3859
3860 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003861 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3862 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3863 };
3864 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865}
3866
3867void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003868 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003870 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003871 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3872 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003876 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003877 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003878 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003879 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880
3881 // The connection appears to be unrecoverably broken.
3882 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003883 if (connection->status == Connection::Status::NORMAL) {
3884 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
3886 if (notify) {
3887 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003888 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3889 connection->getInputChannelName().c_str());
3890
3891 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003892 scoped_unlock unlock(mLock);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003893 mPolicy.notifyInputChannelBroken(connection->getToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003894 };
3895 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
3897 }
3898}
3899
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003900void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003901 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003902 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003903 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
3905}
3906
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003907void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003909 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911}
3912
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003913int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3914 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003915 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003916 if (connection == nullptr) {
3917 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3918 connectionToken.get(), events);
3919 return 0; // remove the callback
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003922 bool notify;
3923 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3924 if (!(events & ALOOPER_EVENT_INPUT)) {
3925 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3926 "events=0x%x",
3927 connection->getInputChannelName().c_str(), events);
3928 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
3930
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003931 nsecs_t currentTime = now();
3932 bool gotOne = false;
3933 status_t status = OK;
3934 for (;;) {
3935 Result<InputPublisher::ConsumerResponse> result =
3936 connection->inputPublisher.receiveConsumerResponse();
3937 if (!result.ok()) {
3938 status = result.error().code();
3939 break;
3940 }
3941
3942 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3943 const InputPublisher::Finished& finish =
3944 std::get<InputPublisher::Finished>(*result);
3945 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3946 finish.consumeTime);
3947 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003948 if (shouldReportMetricsForConnection(*connection)) {
3949 const InputPublisher::Timeline& timeline =
3950 std::get<InputPublisher::Timeline>(*result);
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003951 mLatencyTracker.trackGraphicsLatency(timeline.inputEventId,
3952 connection->getToken(),
3953 std::move(timeline.graphicsTimeline));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003954 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003955 }
3956 gotOne = true;
3957 }
3958 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003959 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003960 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 return 1;
3962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 }
3964
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003965 notify = status != DEAD_OBJECT || !connection->monitor;
3966 if (notify) {
3967 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3968 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3969 status);
3970 }
3971 } else {
3972 // Monitor channels are never explicitly unregistered.
3973 // We do it automatically when the remote endpoint is closed so don't warn about them.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003974 const bool stillHaveWindowHandle = getWindowHandleLocked(connection->getToken()) != nullptr;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003975 notify = !connection->monitor && stillHaveWindowHandle;
3976 if (notify) {
3977 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3978 connection->getInputChannelName().c_str(), events);
3979 }
3980 }
3981
3982 // Remove the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003983 removeInputChannelLocked(connection->getToken(), notify);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003984 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985}
3986
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003987void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003989 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003990 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
3992}
3993
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003994void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003995 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003996 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003997 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08003998 synthesizeCancelationEventsForConnectionLocked(monitor.connection, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003999 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004000 }
4001}
4002
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004004 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004005 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 return;
4007 }
4008
4009 nsecs_t currentTime = now();
4010
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004011 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004012 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004014 if (cancelationEvents.empty()) {
4015 return;
4016 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004017
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004018 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4019 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004020 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004022 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004024
Arthur Hungb3307ee2021-10-14 10:57:37 +00004025 std::string reason = std::string("reason=").append(options.reason);
4026 android_log_event_list(LOGTAG_INPUT_CANCEL)
4027 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4028
hongzuo liu95785e22022-09-06 02:51:35 +00004029 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004030 // The target to use if we don't find a window associated with the channel.
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004031 const InputTarget fallbackTarget{.connection = connection};
4032 const auto& token = connection->getToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004033
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004034 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004035 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004036 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004037
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004038 switch (cancelationEventEntry->type) {
4039 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004040 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004041 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4042 ? std::make_optional(keyEntry.displayId)
4043 : std::nullopt;
4044 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004045 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4046 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004047 } else {
4048 targets.emplace_back(fallbackTarget);
4049 }
4050 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004053 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004054 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004055 const std::optional<int32_t> targetDisplay =
4056 motionEntry.displayId != ADISPLAY_ID_NONE
4057 ? std::make_optional(motionEntry.displayId)
4058 : std::nullopt;
4059 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004060 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004061 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004062 pointerIndex++) {
4063 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4064 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004065 if (mDragState && mDragState->dragWindow->getToken() == token &&
4066 pointerIds.test(mDragState->pointerId)) {
4067 LOG(INFO) << __func__
4068 << ": Canceling drag and drop because the pointers for the drag "
4069 "window are being canceled.";
4070 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4071 mDragState.reset();
4072 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004073 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4074 ftl::Flags<InputTarget::Flags>(), pointerIds,
4075 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004076 } else {
4077 targets.emplace_back(fallbackTarget);
4078 const auto it = mDisplayInfos.find(motionEntry.displayId);
4079 if (it != mDisplayInfos.end()) {
4080 targets.back().displayTransform = it->second.transform;
4081 targets.back().setDefaultPointerTransform(it->second.transform);
4082 }
4083 }
4084 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004085 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004087 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004088 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004089 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4090 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004091 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004092 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004093 break;
4094 }
4095 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004096 case EventEntry::Type::DEVICE_RESET:
4097 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004098 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004099 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004100 break;
4101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004104 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004105 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004107
hongzuo liu95785e22022-09-06 02:51:35 +00004108 // If the outbound queue was previously empty, start the dispatch cycle going.
4109 if (wasEmpty && !connection->outboundQueue.empty()) {
4110 startDispatchCycleLocked(currentTime, connection);
4111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112}
4113
Svet Ganov5d3bc372020-01-26 23:11:07 -08004114void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004115 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004116 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004117 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004118 return;
4119 }
4120
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004121 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004122 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004123
4124 if (downEvents.empty()) {
4125 return;
4126 }
4127
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004128 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004129 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4130 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004131 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004132
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004133 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(connection->getToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004134
hongzuo liu95785e22022-09-06 02:51:35 +00004135 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004136 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004137 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004138 switch (downEventEntry->type) {
4139 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004140 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4141 if (windowHandle != nullptr) {
4142 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004143 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004144 pointerIndex++) {
4145 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4146 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004147 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4148 targetFlags, pointerIds, motionEntry.downTime,
4149 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004150 } else {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08004151 targets.emplace_back(
4152 InputTarget{.connection = connection, .flags = targetFlags});
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004153 const auto it = mDisplayInfos.find(motionEntry.displayId);
4154 if (it != mDisplayInfos.end()) {
4155 targets.back().displayTransform = it->second.transform;
4156 targets.back().setDefaultPointerTransform(it->second.transform);
4157 }
4158 }
4159 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004160 break;
4161 }
4162
4163 case EventEntry::Type::KEY:
4164 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004165 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004166 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004167 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004168 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004169 case EventEntry::Type::SENSOR:
4170 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004171 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004172 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004173 break;
4174 }
4175 }
4176
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004177 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004178 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004179 }
4180
hongzuo liu95785e22022-09-06 02:51:35 +00004181 // If the outbound queue was previously empty, start the dispatch cycle going.
4182 if (wasEmpty && !connection->outboundQueue.empty()) {
4183 startDispatchCycleLocked(downTime, connection);
4184 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004185}
4186
Arthur Hungc539dbb2022-12-08 07:45:36 +00004187void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4188 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4189 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004190 std::shared_ptr<Connection> wallpaperConnection =
4191 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004192 if (wallpaperConnection != nullptr) {
4193 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4194 }
4195 }
4196}
4197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004198std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004199 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4200 nsecs_t splitDownTime) {
4201 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202
4203 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004204 std::vector<PointerProperties> splitPointerProperties;
4205 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004207 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 uint32_t splitPointerCount = 0;
4209
4210 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004213 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004215 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004217 splitPointerProperties.push_back(pointerProperties);
4218 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 splitPointerCount += 1;
4220 }
4221 }
4222
4223 if (splitPointerCount != pointerIds.count()) {
4224 // This is bad. We are missing some of the pointers that we expected to deliver.
4225 // Most likely this indicates that we received an ACTION_MOVE events that has
4226 // different pointer ids than we expected based on the previous ACTION_DOWN
4227 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4228 // in this way.
4229 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004230 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004231 "a broken sequence of pointer ids from the input device: %s",
4232 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004233 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
4235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004236 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4239 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004240 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004242 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004244 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 if (pointerIds.count() == 1) {
4246 // The first/last pointer went down/up.
4247 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004249 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4250 ? AMOTION_EVENT_ACTION_CANCEL
4251 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 } else {
4253 // A secondary pointer went down/up.
4254 uint32_t splitPointerIndex = 0;
4255 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4256 splitPointerIndex += 1;
4257 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 action = maskedAction |
4259 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261 } else {
4262 // An unrelated pointer changed.
4263 action = AMOTION_EVENT_ACTION_MOVE;
4264 }
4265 }
4266
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004267 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4268 logDispatchStateLocked();
4269 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4270 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4271 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004272 }
4273
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004274 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004275 ATRACE_NAME_IF(ATRACE_ENABLED(),
4276 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4277 ").",
4278 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004280 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4281 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 originalMotionEntry.deviceId, originalMotionEntry.source,
4283 originalMotionEntry.displayId,
4284 originalMotionEntry.policyFlags, action,
4285 originalMotionEntry.actionButton,
4286 originalMotionEntry.flags, originalMotionEntry.metaState,
4287 originalMotionEntry.buttonState,
4288 originalMotionEntry.classification,
4289 originalMotionEntry.edgeFlags,
4290 originalMotionEntry.xPrecision,
4291 originalMotionEntry.yPrecision,
4292 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004293 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004294 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 return splitMotionEntry;
4297}
4298
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004299void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4300 std::scoped_lock _l(mLock);
4301 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4302}
4303
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004304void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004305 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004306 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Antonio Kantekf16f2832021-09-28 04:39:20 +00004309 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004311 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004314 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004315 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 } // release lock
4317
4318 if (needWake) {
4319 mLooper->wake();
4320 }
4321}
4322
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004323void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004324 ALOGD_IF(debugInboundEventDetails(),
4325 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4326 ", deviceId=%d, source=%s, displayId=%" PRId32
4327 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4328 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004329 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4330 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4331 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004332 Result<void> keyCheck = validateKeyEvent(args.action);
4333 if (!keyCheck.ok()) {
4334 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 return;
4336 }
4337
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004338 uint32_t policyFlags = args.policyFlags;
4339 int32_t flags = args.flags;
4340 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004341 // InputDispatcher tracks and generates key repeats on behalf of
4342 // whatever notifies it, so repeatCount should always be set to 0
4343 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4345 policyFlags |= POLICY_FLAG_VIRTUAL;
4346 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 if (policyFlags & POLICY_FLAG_FUNCTION) {
4349 metaState |= AMETA_FUNCTION_ON;
4350 }
4351
4352 policyFlags |= POLICY_FLAG_TRUSTED;
4353
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004354 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004356 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4357 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4358 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Michael Wright2b3c3302018-03-02 17:19:13 +00004360 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004361 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004362 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4363 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Antonio Kantekf16f2832021-09-28 04:39:20 +00004367 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 { // acquire lock
4369 mLock.lock();
4370
4371 if (shouldSendKeyToInputFilterLocked(args)) {
4372 mLock.unlock();
4373
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004374 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004375 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 return; // event was consumed by the filter
4377 }
4378
4379 mLock.lock();
4380 }
4381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004383 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4384 args.deviceId, args.source, args.displayId, policyFlags,
4385 args.action, flags, keyCode, args.scanCode, metaState,
4386 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004387 if (mTracer) {
4388 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004391 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 mLock.unlock();
4393 } // release lock
4394
4395 if (needWake) {
4396 mLooper->wake();
4397 }
4398}
4399
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004400bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 return mInputFilterEnabled;
4402}
4403
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004404void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004405 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004406 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004407 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004408 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004409 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4410 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004411 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4412 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4413 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4414 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4415 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004416 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004417 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4418 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004419 i, args.pointerProperties[i].id,
4420 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4421 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4422 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4423 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4424 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4425 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4426 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4427 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4428 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4429 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004432
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004433 Result<void> motionCheck =
4434 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4435 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004436 if (!motionCheck.ok()) {
4437 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4438 return;
4439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004441 if (DEBUG_VERIFY_EVENTS) {
4442 auto [it, _] =
4443 mVerifiersByDisplay.try_emplace(args.displayId,
4444 StringPrintf("display %" PRId32, args.displayId));
4445 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004446 it->second.processMovement(args.deviceId, args.source, args.action,
4447 args.getPointerCount(), args.pointerProperties.data(),
4448 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004449 if (!result.ok()) {
4450 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4451 }
4452 }
4453
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004454 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004456
4457 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004458 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4459 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004460 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4461 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004462 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Antonio Kantekf16f2832021-09-28 04:39:20 +00004465 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 { // acquire lock
4467 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004468 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4469 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4470 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004471 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004472 if (touchStateIt != mTouchStatesByDisplay.end()) {
4473 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004474 if (touchState.hasTouchingPointers(args.deviceId) ||
4475 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004476 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4477 }
4478 }
4479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
4481 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004482 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004483 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004484 displayTransform = it->second.transform;
4485 }
4486
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 mLock.unlock();
4488
4489 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004490 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4491 args.action, args.actionButton, args.flags, args.edgeFlags,
4492 args.metaState, args.buttonState, args.classification,
4493 displayTransform, args.xPrecision, args.yPrecision,
4494 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004495 args.downTime, args.eventTime, args.getPointerCount(),
4496 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
4498 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004499 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 return; // event was consumed by the filter
4501 }
4502
4503 mLock.lock();
4504 }
4505
4506 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004508 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4509 args.deviceId, args.source, args.displayId,
4510 policyFlags, args.action, args.actionButton,
4511 args.flags, args.metaState, args.buttonState,
4512 args.classification, args.edgeFlags, args.xPrecision,
4513 args.yPrecision, args.xCursorPosition,
4514 args.yCursorPosition, args.downTime,
4515 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004516 if (mTracer) {
4517 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004520 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4521 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004522 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004523 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004524 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4525 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4526 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004527 }
4528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004529 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 mLock.unlock();
4531 } // release lock
4532
4533 if (needWake) {
4534 mLooper->wake();
4535 }
4536}
4537
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004538void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004539 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004540 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4541 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004542 args.id, args.eventTime, args.deviceId, args.source,
4543 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004544 }
Chris Yef59a2f42020-10-16 12:55:26 -07004545
Antonio Kantekf16f2832021-09-28 04:39:20 +00004546 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004547 { // acquire lock
4548 mLock.lock();
4549
4550 // Just enqueue a new sensor event.
4551 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004552 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4553 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4554 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004555
4556 needWake = enqueueInboundEventLocked(std::move(newEntry));
4557 mLock.unlock();
4558 } // release lock
4559
4560 if (needWake) {
4561 mLooper->wake();
4562 }
4563}
4564
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004565void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004566 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004567 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4568 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004569 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004570 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004571}
4572
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004573bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004574 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575}
4576
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004577void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004578 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004579 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4580 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004581 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004584 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004586 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587}
4588
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004589void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004590 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004591 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4592 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594
Antonio Kantekf16f2832021-09-28 04:39:20 +00004595 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004597 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004599 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004600 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004601 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004602
4603 for (auto& [_, verifier] : mVerifiersByDisplay) {
4604 verifier.resetDevice(args.deviceId);
4605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 } // release lock
4607
4608 if (needWake) {
4609 mLooper->wake();
4610 }
4611}
4612
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004614 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004615 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4616 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004617 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004618
Antonio Kantekf16f2832021-09-28 04:39:20 +00004619 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004620 { // acquire lock
4621 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004622 auto entry =
4623 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004624 needWake = enqueueInboundEventLocked(std::move(entry));
4625 } // release lock
4626
4627 if (needWake) {
4628 mLooper->wake();
4629 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004630}
4631
Prabir Pradhan5735a322022-04-11 17:23:34 +00004632InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004633 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004634 InputEventInjectionSync syncMode,
4635 std::chrono::milliseconds timeout,
4636 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004637 Result<void> eventValidation = validateInputEvent(*event);
4638 if (!eventValidation.ok()) {
4639 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4640 return InputEventInjectionResult::FAILED;
4641 }
4642
Prabir Pradhan65613802023-02-22 23:36:58 +00004643 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004644 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4645 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4646 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4647 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004648 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004649 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650
Prabir Pradhan5735a322022-04-11 17:23:34 +00004651 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004653 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004654 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4655 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4656 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4657 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4658 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004659 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004660 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004661 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004662 }
4663
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004664 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4665 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4666
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004667 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004669 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004670 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004671 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004672 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004673 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4674 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4675 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004676 int32_t keyCode = incomingKey.getKeyCode();
4677 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004678 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004679 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004680 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4681 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4682 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4685 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004686 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004687
4688 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4689 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004690 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004691 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4692 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4693 std::to_string(t.duration().count()).c_str());
4694 }
4695 }
4696
4697 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004698 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004699 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4700 incomingKey.getEventTime(), resolvedDeviceId,
4701 incomingKey.getSource(), incomingKey.getDisplayId(),
4702 policyFlags, action, flags, keyCode,
4703 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004704 incomingKey.getRepeatCount(),
4705 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004706 if (mTracer) {
4707 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4708 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004709 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 }
4712
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004713 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004714 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004715 const bool isPointerEvent =
4716 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4717 // If a pointer event has no displayId specified, inject it to the default display.
4718 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4719 ? ADISPLAY_ID_DEFAULT
4720 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004721 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722
4723 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004724 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004726 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4727 motionEvent.getAction(), eventTime,
4728 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4730 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4731 std::to_string(t.duration().count()).c_str());
4732 }
4733 }
4734
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004735 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4736 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4737 }
4738
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004739 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004740 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004741 const size_t pointerCount = motionEvent.getPointerCount();
4742 const std::vector<PointerProperties>
4743 pointerProperties(motionEvent.getPointerProperties(),
4744 motionEvent.getPointerProperties() + pointerCount);
4745
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004746 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004747 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004748 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4749 *sampleEventTimes, resolvedDeviceId,
4750 motionEvent.getSource(), displayId, policyFlags,
4751 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004752 motionEvent.getActionButton(), flags,
4753 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004754 motionEvent.getButtonState(),
4755 motionEvent.getClassification(),
4756 motionEvent.getEdgeFlags(),
4757 motionEvent.getXPrecision(),
4758 motionEvent.getYPrecision(),
4759 motionEvent.getRawXCursorPosition(),
4760 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004761 motionEvent.getDownTime(), pointerProperties,
4762 std::vector<PointerCoords>(samplePointerCoords,
4763 samplePointerCoords +
4764 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004765 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004766 if (mTracer) {
4767 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4768 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004769 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004770 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004772 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004773 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004774 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4775 resolvedDeviceId, motionEvent.getSource(), displayId,
4776 policyFlags, motionEvent.getAction(),
4777 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004778 motionEvent.getMetaState(), motionEvent.getButtonState(),
4779 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4780 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4781 motionEvent.getRawXCursorPosition(),
4782 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4783 pointerProperties,
4784 std::vector<PointerCoords>(samplePointerCoords,
4785 samplePointerCoords +
4786 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004787 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4788 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004789 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004790 }
4791 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004795 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004800 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004801 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004802 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004803 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004804 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004805 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807
4808 mLock.unlock();
4809
4810 if (needWake) {
4811 mLooper->wake();
4812 }
4813
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004814 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004816 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004818 if (syncMode == InputEventInjectionSync::NONE) {
4819 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 } else {
4821 for (;;) {
4822 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 break;
4825 }
4826
4827 nsecs_t remainingTimeout = endTime - now();
4828 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004829 if (DEBUG_INJECTION) {
4830 ALOGD("injectInputEvent - Timed out waiting for injection result "
4831 "to become available.");
4832 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004833 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 break;
4835 }
4836
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004837 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004840 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4841 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004843 if (DEBUG_INJECTION) {
4844 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4845 injectionState->pendingForegroundDispatches);
4846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 nsecs_t remainingTimeout = endTime - now();
4848 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004849 if (DEBUG_INJECTION) {
4850 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4851 "dispatches to finish.");
4852 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004853 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 break;
4855 }
4856
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004857 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 }
4859 }
4860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 } // release lock
4862
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004863 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004864 LOG(INFO) << "injectInputEvent - Finished with result "
4865 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867
4868 return injectionResult;
4869}
4870
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004871std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004872 std::array<uint8_t, 32> calculatedHmac;
4873 std::unique_ptr<VerifiedInputEvent> result;
4874 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004875 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004876 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4877 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4878 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004879 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004880 break;
4881 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004882 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004883 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4884 VerifiedMotionEvent verifiedMotionEvent =
4885 verifiedMotionEventFromMotionEvent(motionEvent);
4886 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004887 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004888 break;
4889 }
4890 default: {
4891 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4892 return nullptr;
4893 }
4894 }
4895 if (calculatedHmac == INVALID_HMAC) {
4896 return nullptr;
4897 }
tyiu1573a672023-02-21 22:38:32 +00004898 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004899 return nullptr;
4900 }
4901 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004902}
4903
Prabir Pradhan24047542023-11-02 17:14:59 +00004904void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004905 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004906 if (!entry.injectionState) {
4907 // Not an injected event.
4908 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004910
4911 InjectionState& injectionState = *entry.injectionState;
4912 if (DEBUG_INJECTION) {
4913 LOG(INFO) << "Setting input event injection result to "
4914 << ftl::enum_string(injectionResult);
4915 }
4916
4917 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4918 // Log the outcome since the injector did not wait for the injection result.
4919 switch (injectionResult) {
4920 case InputEventInjectionResult::SUCCEEDED:
4921 ALOGV("Asynchronous input event injection succeeded.");
4922 break;
4923 case InputEventInjectionResult::TARGET_MISMATCH:
4924 ALOGV("Asynchronous input event injection target mismatch.");
4925 break;
4926 case InputEventInjectionResult::FAILED:
4927 ALOGW("Asynchronous input event injection failed.");
4928 break;
4929 case InputEventInjectionResult::TIMED_OUT:
4930 ALOGW("Asynchronous input event injection timed out.");
4931 break;
4932 case InputEventInjectionResult::PENDING:
4933 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4934 break;
4935 }
4936 }
4937
4938 injectionState.injectionResult = injectionResult;
4939 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940}
4941
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004942void InputDispatcher::transformMotionEntryForInjectionLocked(
4943 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004944 // Input injection works in the logical display coordinate space, but the input pipeline works
4945 // display space, so we need to transform the injected events accordingly.
4946 const auto it = mDisplayInfos.find(entry.displayId);
4947 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004948 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004949
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004950 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4951 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4952 const vec2 cursor =
4953 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4954 {entry.xCursorPosition, entry.yCursorPosition});
4955 entry.xCursorPosition = cursor.x;
4956 entry.yCursorPosition = cursor.y;
4957 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004958 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004959 entry.pointerCoords[i] =
4960 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4961 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004962 }
4963}
4964
Prabir Pradhan24047542023-11-02 17:14:59 +00004965void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004966 if (entry.injectionState) {
4967 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 }
4969}
4970
Prabir Pradhan24047542023-11-02 17:14:59 +00004971void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004972 if (entry.injectionState) {
4973 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004975 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004976 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 }
4978 }
4979}
4980
chaviw98318de2021-05-19 16:45:23 -05004981const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004982 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004983 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004984 auto it = mWindowHandlesByDisplay.find(displayId);
4985 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004986}
4987
chaviw98318de2021-05-19 16:45:23 -05004988sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004989 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004990 if (windowHandleToken == nullptr) {
4991 return nullptr;
4992 }
4993
Prabir Pradhan16463382023-10-12 23:03:19 +00004994 if (!displayId) {
4995 // Look through all displays.
4996 for (auto& it : mWindowHandlesByDisplay) {
4997 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4998 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4999 if (windowHandle->getToken() == windowHandleToken) {
5000 return windowHandle;
5001 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005004 return nullptr;
5005 }
5006
Prabir Pradhan16463382023-10-12 23:03:19 +00005007 // Only look through the requested display.
5008 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005009 if (windowHandle->getToken() == windowHandleToken) {
5010 return windowHandle;
5011 }
5012 }
5013 return nullptr;
5014}
5015
chaviw98318de2021-05-19 16:45:23 -05005016sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5017 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005018 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005019 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5020 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005021 if (handle->getId() == windowHandle->getId() &&
5022 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005023 if (windowHandle->getInfo()->displayId != it.first) {
5024 ALOGE("Found window %s in display %" PRId32
5025 ", but it should belong to display %" PRId32,
5026 windowHandle->getName().c_str(), it.first,
5027 windowHandle->getInfo()->displayId);
5028 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005029 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 }
5032 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005033 return nullptr;
5034}
5035
chaviw98318de2021-05-19 16:45:23 -05005036sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005037 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5038 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039}
5040
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005041ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5042 auto displayInfoIt = mDisplayInfos.find(displayId);
5043 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5044 : kIdentityTransform;
5045}
5046
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005047bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5048 const MotionEntry& motionEntry) const {
5049 const WindowInfo& info = *window->getInfo();
5050
5051 // Skip spy window targets that are not valid for targeted injection.
5052 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005053 return false;
5054 }
5055
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005056 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5057 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5058 return false;
5059 }
5060
5061 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5062 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5063 window->getName().c_str());
5064 return false;
5065 }
5066
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005067 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005068 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005069 ALOGW("Not sending touch to %s because there's no corresponding connection",
5070 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005071 return false;
5072 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005073
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005074 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005075 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005076 return false;
5077 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005078
5079 // Drop events that can't be trusted due to occlusion
5080 const auto [x, y] = resolveTouchedPosition(motionEntry);
5081 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5082 if (!isTouchTrustedLocked(occlusionInfo)) {
5083 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005084 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005085 for (const auto& log : occlusionInfo.debugInfo) {
5086 ALOGD("%s", log.c_str());
5087 }
5088 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005089 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5090 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005091 return false;
5092 }
5093
5094 // Drop touch events if requested by input feature
5095 if (shouldDropInput(motionEntry, window)) {
5096 return false;
5097 }
5098
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005099 // Ignore touches if stylus is down anywhere on screen
5100 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5101 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5102 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5103 return false;
5104 }
5105
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005106 return true;
5107}
5108
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005109void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005110 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5111 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005112 // Remove all handles on a display if there are no windows left.
5113 mWindowHandlesByDisplay.erase(displayId);
5114 return;
5115 }
5116
5117 // Since we compare the pointer of input window handles across window updates, we need
5118 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005119 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5120 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5121 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005122 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005123 }
5124
chaviw98318de2021-05-19 16:45:23 -05005125 std::vector<sp<WindowInfoHandle>> newHandles;
5126 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005127 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005128 if (getConnectionLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005129 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005130 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005131 const bool canReceiveInput =
5132 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5133 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005134 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005135 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005136 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005137 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005138 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005139 }
5140
5141 if (info->displayId != displayId) {
5142 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5143 handle->getName().c_str(), displayId, info->displayId);
5144 continue;
5145 }
5146
Robert Carredd13602020-04-13 17:24:34 -07005147 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5148 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005149 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005150 oldHandle->updateFrom(handle);
5151 newHandles.push_back(oldHandle);
5152 } else {
5153 newHandles.push_back(handle);
5154 }
5155 }
5156
5157 // Insert or replace
5158 mWindowHandlesByDisplay[displayId] = newHandles;
5159}
5160
Arthur Hungb92218b2018-08-14 12:00:21 +08005161/**
5162 * Called from InputManagerService, update window handle list by displayId that can receive input.
5163 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5164 * If set an empty list, remove all handles from the specific display.
5165 * For focused handle, check if need to change and send a cancel event to previous one.
5166 * For removed handle, check if need to send a cancel event if already in touch.
5167 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005168void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005169 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005170 if (DEBUG_FOCUS) {
5171 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005172 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005173 windowList += iwh->getName() + " ";
5174 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005175 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
Prabir Pradhand65552b2021-10-07 11:23:50 -07005178 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005179 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005180 const WindowInfo& info = *window->getInfo();
5181
5182 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005183 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005184 if (noInputWindow && window->getToken() != nullptr) {
5185 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5186 window->getName().c_str());
5187 window->releaseChannel();
5188 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005189
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005190 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005191 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5192 !info.inputConfig.test(
5193 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005194 "%s has feature SPY, but is not a trusted overlay.",
5195 window->getName().c_str());
5196
Prabir Pradhand65552b2021-10-07 11:23:50 -07005197 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005198 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5199 !info.inputConfig.test(
5200 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005201 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5202 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005203 }
5204
Arthur Hung72d8dc32020-03-28 00:48:39 +00005205 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005206 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207
chaviw98318de2021-05-19 16:45:23 -05005208 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005209
chaviw98318de2021-05-19 16:45:23 -05005210 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005211
Vishnu Nairc519ff72021-01-21 08:23:08 -08005212 std::optional<FocusResolver::FocusChanges> changes =
5213 mFocusResolver.setInputWindows(displayId, windowHandles);
5214 if (changes) {
5215 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005218 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5219 mTouchStatesByDisplay.find(displayId);
5220 if (stateIt != mTouchStatesByDisplay.end()) {
5221 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005222 for (size_t i = 0; i < state.windows.size();) {
5223 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005224 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005225 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5226 << " in display %" << displayId;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005227 std::shared_ptr<Connection> touchedConnection =
5228 getConnectionLocked(touchedWindow.windowHandle->getToken());
5229 if (touchedConnection != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005230 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005231 "touched window was removed");
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005232 synthesizeCancelationEventsForConnectionLocked(touchedConnection, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005233 // Since we are about to drop the touch, cancel the events for the wallpaper as
5234 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005235 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005236 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5237 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005238 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005239 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005242 state.windows.erase(state.windows.begin() + i);
5243 } else {
5244 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
5246 }
arthurhungb89ccb02020-12-30 16:19:01 +08005247
arthurhung6d4bed92021-03-17 11:59:33 +08005248 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005249 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005250 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005251 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005252 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005253 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5254 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005255 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005256 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005257 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005258
Arthur Hung72d8dc32020-03-28 00:48:39 +00005259 // Release information for windows that are no longer present.
5260 // This ensures that unused input channels are released promptly.
5261 // Otherwise, they might stick around until the window handle is destroyed
5262 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005263 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005264 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005265 if (DEBUG_FOCUS) {
5266 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005267 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005268 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005269 }
chaviw291d88a2019-02-14 10:33:58 -08005270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271}
5272
5273void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005274 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005275 if (DEBUG_FOCUS) {
5276 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5277 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5278 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005280 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005281 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 } // release lock
5283
5284 // Wake up poll loop since it may need to make new input dispatching choices.
5285 mLooper->wake();
5286}
5287
Vishnu Nair599f1412021-06-21 10:39:58 -07005288void InputDispatcher::setFocusedApplicationLocked(
5289 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5290 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5291 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5292
5293 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5294 return; // This application is already focused. No need to wake up or change anything.
5295 }
5296
5297 // Set the new application handle.
5298 if (inputApplicationHandle != nullptr) {
5299 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5300 } else {
5301 mFocusedApplicationHandlesByDisplay.erase(displayId);
5302 }
5303
5304 // No matter what the old focused application was, stop waiting on it because it is
5305 // no longer focused.
5306 resetNoFocusedWindowTimeoutLocked();
5307}
5308
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005309void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5310 if (interval.count() < 0) {
5311 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5312 }
5313 std::scoped_lock _l(mLock);
5314 mMinTimeBetweenUserActivityPokes = interval;
5315}
5316
Tiger Huang721e26f2018-07-24 22:26:19 +08005317/**
5318 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5319 * the display not specified.
5320 *
5321 * We track any unreleased events for each window. If a window loses the ability to receive the
5322 * released event, we will send a cancel event to it. So when the focused display is changed, we
5323 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5324 * display. The display-specified events won't be affected.
5325 */
5326void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005327 if (DEBUG_FOCUS) {
5328 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5329 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005331 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005332
5333 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005334 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005335 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005336 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005337 std::shared_ptr<Connection> connection = getConnectionLocked(oldFocusedWindowToken);
5338 if (connection != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005339 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005340 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005341 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005342 options.displayId = ADISPLAY_ID_NONE;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005343 synthesizeCancelationEventsForConnectionLocked(connection, options);
Tiger Huang721e26f2018-07-24 22:26:19 +08005344 }
5345 }
5346 mFocusedDisplayId = displayId;
5347
Chris Ye3c2d6f52020-08-09 10:39:48 -07005348 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005349 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005350 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005351
Vishnu Nairad321cd2020-08-20 16:40:21 -07005352 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005353 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005354 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005355 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005356 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005357 }
5358 }
5359 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005360 } // release lock
5361
5362 // Wake up poll loop since it may need to make new input dispatching choices.
5363 mLooper->wake();
5364}
5365
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005367 if (DEBUG_FOCUS) {
5368 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370
5371 bool changed;
5372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374
5375 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5376 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005377 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 }
5379
5380 if (mDispatchEnabled && !enabled) {
5381 resetAndDropEverythingLocked("dispatcher is being disabled");
5382 }
5383
5384 mDispatchEnabled = enabled;
5385 mDispatchFrozen = frozen;
5386 changed = true;
5387 } else {
5388 changed = false;
5389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 } // release lock
5391
5392 if (changed) {
5393 // Wake up poll loop since it may need to make new input dispatching choices.
5394 mLooper->wake();
5395 }
5396}
5397
5398void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005399 if (DEBUG_FOCUS) {
5400 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402
5403 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005404 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405
5406 if (mInputFilterEnabled == enabled) {
5407 return;
5408 }
5409
5410 mInputFilterEnabled = enabled;
5411 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5412 } // release lock
5413
5414 // Wake up poll loop since there might be work to do to drop everything.
5415 mLooper->wake();
5416}
5417
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005418bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005419 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005420 bool needWake = false;
5421 {
5422 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005423 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005424 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005425 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005426 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5427 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005428 mTouchModePerDisplay.count(displayId) == 0
5429 ? "not set"
5430 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5431
Antonio Kantek15beb512022-06-13 22:35:41 +00005432 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5433 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005434 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005435 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005436 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005437 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5438 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005439 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005440 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005441 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005442 return false;
5443 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005444 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005445 mTouchModePerDisplay[displayId] = inTouchMode;
5446 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5447 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005448 needWake = enqueueInboundEventLocked(std::move(entry));
5449 } // release lock
5450
5451 if (needWake) {
5452 mLooper->wake();
5453 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005454 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005455}
5456
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005457bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005458 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5459 if (focusedToken == nullptr) {
5460 return false;
5461 }
5462 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5463 return isWindowOwnedBy(windowHandle, pid, uid);
5464}
5465
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005466bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005467 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5468 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5469 const sp<WindowInfoHandle> windowHandle =
5470 getWindowHandleLocked(connectionToken);
5471 return isWindowOwnedBy(windowHandle, pid, uid);
5472 }) != mInteractionConnectionTokens.end();
5473}
5474
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005475void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5476 if (opacity < 0 || opacity > 1) {
5477 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5478 return;
5479 }
5480
5481 std::scoped_lock lock(mLock);
5482 mMaximumObscuringOpacityForTouch = opacity;
5483}
5484
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005485std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5486InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005487 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5488 for (TouchedWindow& w : state.windows) {
5489 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005490 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005491 }
5492 }
5493 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005494 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005495}
5496
arthurhungb89ccb02020-12-30 16:19:01 +08005497bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5498 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005499 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005500 if (DEBUG_FOCUS) {
5501 ALOGD("Trivial transfer to same window.");
5502 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005503 return true;
5504 }
5505
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005507 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508
Arthur Hungabbb9d82021-09-01 14:52:30 +00005509 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005510 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005511
Arthur Hungabbb9d82021-09-01 14:52:30 +00005512 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005513 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 return false;
5515 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005516 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5517 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005518 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5519 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005520 return false;
5521 }
5522 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005523
Arthur Hungabbb9d82021-09-01 14:52:30 +00005524 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5525 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005526 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005527 return false;
5528 }
5529
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005530 if (DEBUG_FOCUS) {
5531 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005532 touchedWindow->windowHandle->getName().c_str(),
5533 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535
Arthur Hungabbb9d82021-09-01 14:52:30 +00005536 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005537 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005538 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005539 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005540 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541
Arthur Hungabbb9d82021-09-01 14:52:30 +00005542 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005543 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005544 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005545 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005546 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005547 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005548 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005549 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005550 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551
Arthur Hungabbb9d82021-09-01 14:52:30 +00005552 // Store the dragging window.
5553 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005554 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005555 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5556 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005557 return false;
5558 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005559 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005560 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005561 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563
Arthur Hungabbb9d82021-09-01 14:52:30 +00005564 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005565 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5566 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005567 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005568 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005569 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5570 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005572 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5573 newTargetFlags);
5574
5575 // Check if the wallpaper window should deliver the corresponding event.
5576 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005577 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 } // release lock
5580
5581 // Wake up poll loop since it may need to make new input dispatching choices.
5582 mLooper->wake();
5583 return true;
5584}
5585
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005586/**
5587 * Get the touched foreground window on the given display.
5588 * Return null if there are no windows touched on that display, or if more than one foreground
5589 * window is being touched.
5590 */
5591sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5592 auto stateIt = mTouchStatesByDisplay.find(displayId);
5593 if (stateIt == mTouchStatesByDisplay.end()) {
5594 ALOGI("No touch state on display %" PRId32, displayId);
5595 return nullptr;
5596 }
5597
5598 const TouchState& state = stateIt->second;
5599 sp<WindowInfoHandle> touchedForegroundWindow;
5600 // If multiple foreground windows are touched, return nullptr
5601 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005602 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005603 if (touchedForegroundWindow != nullptr) {
5604 ALOGI("Two or more foreground windows: %s and %s",
5605 touchedForegroundWindow->getName().c_str(),
5606 window.windowHandle->getName().c_str());
5607 return nullptr;
5608 }
5609 touchedForegroundWindow = window.windowHandle;
5610 }
5611 }
5612 return touchedForegroundWindow;
5613}
5614
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005615// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005616bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005617 sp<IBinder> fromToken;
5618 { // acquire lock
5619 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005620 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005621 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005622 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5623 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005624 return false;
5625 }
5626
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005627 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5628 if (from == nullptr) {
5629 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5630 return false;
5631 }
5632
5633 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005634 } // release lock
5635
5636 return transferTouchFocus(fromToken, destChannelToken);
5637}
5638
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005640 if (DEBUG_FOCUS) {
5641 ALOGD("Resetting and dropping all events (%s).", reason);
5642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643
Michael Wrightfb04fd52022-11-24 22:31:11 +00005644 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 synthesizeCancelationEventsForAllConnectionsLocked(options);
5646
5647 resetKeyRepeatLocked();
5648 releasePendingEventLocked();
5649 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005650 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005652 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005653 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654}
5655
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005656void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005657 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658 dumpDispatchStateLocked(dump);
5659
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005660 std::istringstream stream(dump);
5661 std::string line;
5662
5663 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005664 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 }
5666}
5667
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005668std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005669 std::string dump;
5670
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005671 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5672 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005673
5674 std::string windowName = "None";
5675 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005676 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005677 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5678 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5679 : "token has capture without window";
5680 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005681 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005682
5683 return dump;
5684}
5685
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005686void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005687 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5688 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5689 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005690 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691
Tiger Huang721e26f2018-07-24 22:26:19 +08005692 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5693 dump += StringPrintf(INDENT "FocusedApplications:\n");
5694 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5695 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005696 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005697 const std::chrono::duration timeout =
5698 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005699 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005700 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005701 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005704 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005706
Vishnu Nairc519ff72021-01-21 08:23:08 -08005707 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005708 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005710 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005712 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005713 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5714 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719
arthurhung6d4bed92021-03-17 11:59:33 +08005720 if (mDragState) {
5721 dump += StringPrintf(INDENT "DragState:\n");
5722 mDragState->dump(dump, INDENT2);
5723 }
5724
Arthur Hungb92218b2018-08-14 12:00:21 +08005725 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005726 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5727 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5728 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5729 const auto& displayInfo = it->second;
5730 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5731 displayInfo.logicalHeight);
5732 displayInfo.transform.dump(dump, "transform", INDENT4);
5733 } else {
5734 dump += INDENT2 "No DisplayInfo found!\n";
5735 }
5736
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005737 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005738 dump += INDENT2 "Windows:\n";
5739 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005740 dump += StringPrintf(INDENT3 "%zu: %s", i,
5741 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005742 }
5743 } else {
5744 dump += INDENT2 "Windows: <none>\n";
5745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 }
5747 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005748 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
5750
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005751 if (!mGlobalMonitorsByDisplay.empty()) {
5752 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5753 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005754 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758 }
5759
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761
5762 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005763 if (!mRecentQueue.empty()) {
5764 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005765 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005766 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005767 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005768 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005771 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 }
5773
5774 // Dump event currently being dispatched.
5775 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005776 dump += INDENT "PendingEvent:\n";
5777 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005778 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005779 dump += StringPrintf(", age=%" PRId64 "ms\n",
5780 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
5785 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005786 if (!mInboundQueue.empty()) {
5787 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005788 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005789 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005790 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005794 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 }
5796
Prabir Pradhancef936d2021-07-21 16:17:52 +00005797 if (!mCommandQueue.empty()) {
5798 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5799 } else {
5800 dump += INDENT "CommandQueue: <empty>\n";
5801 }
5802
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005803 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005804 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005805 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005806 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005807 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005808 connection->inputChannel->getFd(),
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005809 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005810 connection->getWindowName().c_str(),
5811 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005812 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005814 if (!connection->outboundQueue.empty()) {
5815 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5816 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005817 dump += dumpQueue(connection->outboundQueue, currentTime);
5818
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005820 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 }
5822
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005823 if (!connection->waitQueue.empty()) {
5824 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5825 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005826 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005828 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005830 std::string inputStateDump = streamableToString(connection->inputState);
5831 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005832 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005833 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835 }
5836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005837 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838 }
5839
Antonio Kantek15beb512022-06-13 22:35:41 +00005840 if (!mTouchModePerDisplay.empty()) {
5841 dump += INDENT "TouchModePerDisplay:\n";
5842 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5843 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5844 std::to_string(touchMode).c_str());
5845 }
5846 } else {
5847 dump += INDENT "TouchModePerDisplay: <none>\n";
5848 }
5849
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005850 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005851 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5852 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5853 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005854 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005855 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005856 dump += INDENT "InputTracer: ";
5857 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858}
5859
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005860void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005861 const size_t numMonitors = monitors.size();
5862 for (size_t i = 0; i < numMonitors; i++) {
5863 const Monitor& monitor = monitors[i];
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005864 const std::shared_ptr<Connection>& connection = monitor.connection;
5865 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00005866 dump += "\n";
5867 }
5868}
5869
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005870class LooperEventCallback : public LooperCallback {
5871public:
5872 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5873 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5874
5875private:
5876 std::function<int(int events)> mCallback;
5877};
5878
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005879Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005880 if (DEBUG_CHANNEL_CREATION) {
5881 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005884 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005885 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005886 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005887
5888 if (result) {
5889 return base::Error(result) << "Failed to open input channel pair with name " << name;
5890 }
5891
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005893 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005894 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005895 const int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005896 std::shared_ptr<Connection> connection =
5897 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5898 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005899
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005900 auto [_, inserted] = mConnectionsByToken.try_emplace(token, connection);
5901 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005902 ALOGE("Created a new connection, but the token %p is already known", token.get());
5903 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005904
5905 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5906 this, std::placeholders::_1, token);
5907
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005908 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005909 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 } // release lock
5911
5912 // Wake the looper because some connections have changed.
5913 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005914 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915}
5916
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005917Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005918 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005919 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005920 std::shared_ptr<InputChannel> serverChannel;
5921 std::unique_ptr<InputChannel> clientChannel;
5922 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5923 if (result) {
5924 return base::Error(result) << "Failed to open input channel pair with name " << name;
5925 }
5926
Michael Wright3dd60e22019-03-27 22:06:44 +00005927 { // acquire lock
5928 std::scoped_lock _l(mLock);
5929
5930 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005931 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5932 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005933 }
5934
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005935 std::shared_ptr<Connection> connection =
5936 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005937 const sp<IBinder>& token = serverChannel->getConnectionToken();
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005938 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005939
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005940 auto [_, inserted] = mConnectionsByToken.emplace(token, connection);
5941 if (!inserted) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005942 ALOGE("Created a new connection, but the token %p is already known", token.get());
5943 }
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005944
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005945 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5946 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005947
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08005948 mGlobalMonitorsByDisplay[displayId].emplace_back(connection, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005949
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005950 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005951 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005952 }
Garfield Tan15601662020-09-22 15:32:38 -07005953
Michael Wright3dd60e22019-03-27 22:06:44 +00005954 // Wake the looper because some connections have changed.
5955 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005956 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005957}
5958
Garfield Tan15601662020-09-22 15:32:38 -07005959status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005961 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962
Harry Cutts33476232023-01-30 19:57:29 +00005963 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 if (status) {
5965 return status;
5966 }
5967 } // release lock
5968
5969 // Wake the poll loop because removing the connection may have changed the current
5970 // synchronization state.
5971 mLooper->wake();
5972 return OK;
5973}
5974
Garfield Tan15601662020-09-22 15:32:38 -07005975status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5976 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005977 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005978 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005979 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 return BAD_VALUE;
5981 }
5982
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005983 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005984
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005986 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987 }
5988
Siarhei Vishniakou8d660132024-01-11 16:48:44 -08005989 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990
5991 nsecs_t currentTime = now();
5992 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5993
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005994 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 return OK;
5996}
5997
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005998void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005999 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6000 auto& [displayId, monitors] = *it;
6001 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006002 return monitor.connection->getToken() == connectionToken;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006003 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006004
Michael Wright3dd60e22019-03-27 22:06:44 +00006005 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006006 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006007 } else {
6008 ++it;
6009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 }
6011}
6012
Michael Wright3dd60e22019-03-27 22:06:44 +00006013status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006014 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006015 return pilferPointersLocked(token);
6016}
Michael Wright3dd60e22019-03-27 22:06:44 +00006017
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006018status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006019 const std::shared_ptr<Connection> requestingConnection = getConnectionLocked(token);
6020 if (!requestingConnection) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006021 LOG(WARNING)
6022 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006023 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006024 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006025
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006026 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006027 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006028 LOG(WARNING)
6029 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6030 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006031 return BAD_VALUE;
6032 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006033 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006034 if (deviceIds.empty()) {
6035 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006036 return BAD_VALUE;
6037 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006038
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006039 for (const DeviceId deviceId : deviceIds) {
6040 TouchState& state = *statePtr;
6041 TouchedWindow& window = *windowPtr;
6042 // Send cancel events to all the input channels we're stealing from.
6043 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6044 "input channel stole pointer stream");
6045 options.deviceId = deviceId;
6046 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006047 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6048 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006049 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006050
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006051 std::string canceledWindows;
6052 for (const TouchedWindow& w : state.windows) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006053 const std::shared_ptr<Connection> connection =
6054 getConnectionLocked(w.windowHandle->getToken());
6055 if (connection != nullptr && connection->getToken() != token) {
6056 synthesizeCancelationEventsForConnectionLocked(connection, options);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006057 canceledWindows += canceledWindows.empty() ? "[" : ", ";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006058 canceledWindows += connection->getInputChannelName();
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006059 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006060 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006061 canceledWindows += canceledWindows.empty() ? "[]" : "]";
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006062 LOG(INFO) << "Channel " << requestingConnection->getInputChannelName()
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006063 << " is stealing input gesture for device " << deviceId << " from "
6064 << canceledWindows;
6065
6066 // Prevent the gesture from being sent to any other windows.
6067 // This only blocks relevant pointers to be sent to other windows
6068 window.addPilferingPointers(deviceId, pointerIds);
6069
6070 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006072 return OK;
6073}
6074
Prabir Pradhan99987712020-11-10 18:43:05 -08006075void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6076 { // acquire lock
6077 std::scoped_lock _l(mLock);
6078 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006079 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006080 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6081 windowHandle != nullptr ? windowHandle->getName().c_str()
6082 : "token without window");
6083 }
6084
Vishnu Nairc519ff72021-01-21 08:23:08 -08006085 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006086 if (focusedToken != windowToken) {
6087 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6088 enabled ? "enable" : "disable");
6089 return;
6090 }
6091
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006092 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006093 ALOGW("Ignoring request to %s Pointer Capture: "
6094 "window has %s requested pointer capture.",
6095 enabled ? "enable" : "disable", enabled ? "already" : "not");
6096 return;
6097 }
6098
Christine Franksb768bb42021-11-29 12:11:31 -08006099 if (enabled) {
6100 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6101 mIneligibleDisplaysForPointerCapture.end(),
6102 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6103 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6104 return;
6105 }
6106 }
6107
Prabir Pradhan99987712020-11-10 18:43:05 -08006108 setPointerCaptureLocked(enabled);
6109 } // release lock
6110
6111 // Wake the thread to process command entries.
6112 mLooper->wake();
6113}
6114
Christine Franksb768bb42021-11-29 12:11:31 -08006115void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6116 { // acquire lock
6117 std::scoped_lock _l(mLock);
6118 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6119 if (!isEligible) {
6120 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6121 }
6122 } // release lock
6123}
6124
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006125std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006126 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006127 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006128 if (monitor.connection->getToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006129 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006130 }
6131 }
6132 }
6133 return std::nullopt;
6134}
6135
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006136std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6137 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006138 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006139 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006140 }
6141
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006142 for (const auto& [token, connection] : mConnectionsByToken) {
6143 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006144 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145 }
6146 }
Robert Carr4e670e52018-08-15 13:26:12 -07006147
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006148 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149}
6150
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006151std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006152 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006153 if (connection == nullptr) {
6154 return "<nullptr>";
6155 }
6156 return connection->getInputChannelName();
6157}
6158
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006159void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006160 mAnrTracker.eraseToken(connection->getToken());
6161 mConnectionsByToken.erase(connection->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006162}
6163
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006165 const std::shared_ptr<Connection>& connection,
6166 uint32_t seq, bool handled,
6167 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006168 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006169 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006170
6171 { // Start critical section
6172 auto dispatchEntryIt =
6173 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6174 [seq](auto& e) { return e->seq == seq; });
6175 if (dispatchEntryIt == connection->waitQueue.end()) {
6176 return;
6177 }
6178
6179 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6180
6181 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6182 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6183 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6184 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6185 }
6186 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006187 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id, connection->getToken(),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006188 dispatchEntry.deliveryTime, consumeTime, finishTime);
6189 }
6190
6191 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006192 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6193 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006194 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006195 }
6196 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197
6198 // Dequeue the event and start the next cycle.
6199 // Because the lock might have been released, it is possible that the
6200 // contents of the wait queue to have been drained, so we need to double-check
6201 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006202 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6203 [seq](auto& e) { return e->seq == seq; });
6204 if (entryIt != connection->waitQueue.end()) {
6205 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6206 connection->waitQueue.erase(entryIt);
6207
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006208 const sp<IBinder>& connectionToken = connection->getToken();
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6210 if (!connection->responsive) {
6211 connection->responsive = isConnectionResponsive(*connection);
6212 if (connection->responsive) {
6213 // The connection was unresponsive, and now it's responsive.
6214 processConnectionResponsiveLocked(*connection);
6215 }
6216 }
6217 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006218 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006219 const InputTarget target{.connection = connection, .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006220 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006221 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006222 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006223 }
6224
6225 // Start the next dispatch cycle for this connection.
6226 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227}
6228
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6230 const sp<IBinder>& newToken) {
6231 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6232 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006233 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006234 };
6235 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236}
6237
Prabir Pradhancef936d2021-07-21 16:17:52 +00006238void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6239 auto command = [this, token, x, y]() REQUIRES(mLock) {
6240 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006241 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 };
6243 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006244}
6245
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006246void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006247 if (connection == nullptr) {
6248 LOG_ALWAYS_FATAL("Caller must check for nullness");
6249 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006250 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6251 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006252 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006253 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006254 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006255 return;
6256 }
6257 /**
6258 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6259 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6260 * has changed. This could cause newer entries to time out before the already dispatched
6261 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6262 * processes the events linearly. So providing information about the oldest entry seems to be
6263 * most useful.
6264 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006265 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6266 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006267 std::string reason =
6268 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006269 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006270 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006271 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006272 sp<IBinder> connectionToken = connection->getToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006273 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006274
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006275 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6276
6277 // Stop waking up for events on this connection, it is already unresponsive
6278 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006279}
6280
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006281void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6282 std::string reason =
6283 StringPrintf("%s does not have a focused window", application->getName().c_str());
6284 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285
Yabin Cui8eb9c552023-06-08 18:05:07 +00006286 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006288 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006289 };
6290 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006291}
6292
chaviw98318de2021-05-19 16:45:23 -05006293void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006294 const std::string& reason) {
6295 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6296 updateLastAnrStateLocked(windowLabel, reason);
6297}
6298
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006299void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6300 const std::string& reason) {
6301 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302 updateLastAnrStateLocked(windowLabel, reason);
6303}
6304
6305void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6306 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006308 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 struct tm tm;
6310 localtime_r(&t, &tm);
6311 char timestr[64];
6312 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006313 mLastAnrState.clear();
6314 mLastAnrState += INDENT "ANR:\n";
6315 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006316 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6317 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006318 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319}
6320
Prabir Pradhancef936d2021-07-21 16:17:52 +00006321void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006322 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006323 const KeyEvent event = createKeyEvent(entry);
6324 nsecs_t delay = 0;
6325 { // release lock
6326 scoped_unlock unlock(mLock);
6327 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006328 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006329 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6330 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6331 std::to_string(t.duration().count()).c_str());
6332 }
6333 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334
6335 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006336 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006337 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006338 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006339 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006340 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006341 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343}
6344
Prabir Pradhancef936d2021-07-21 16:17:52 +00006345void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006346 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006347 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006348 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006349 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006350 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006351 };
6352 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006353}
6354
Prabir Pradhanedd96402022-02-15 01:46:16 -08006355void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006356 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006357 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006358 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006359 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006360 };
6361 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006362}
6363
6364/**
6365 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6366 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6367 * command entry to the command queue.
6368 */
6369void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6370 std::string reason) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006371 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006372 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006373 if (connection.monitor) {
6374 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6375 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006376 pid = findMonitorPidByTokenLocked(connectionToken);
6377 } else {
6378 // The connection is a window
6379 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6380 reason.c_str());
6381 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6382 if (handle != nullptr) {
6383 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006384 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006385 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006386 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006387}
6388
6389/**
6390 * Tell the policy that a connection has become responsive so that it can stop ANR.
6391 */
6392void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006393 const sp<IBinder>& connectionToken = connection.getToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006394 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006395 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006396 pid = findMonitorPidByTokenLocked(connectionToken);
6397 } else {
6398 // The connection is a window
6399 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6400 if (handle != nullptr) {
6401 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006402 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006403 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006404 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006405}
6406
Prabir Pradhan24047542023-11-02 17:14:59 +00006407std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006408 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006409 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006410 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006411 if (!handled) {
6412 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006413 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006414 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006415 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006417
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006418 // Get the fallback key state.
6419 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006420 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006421 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006422 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006423 connection->inputState.removeFallbackKey(originalKeyCode);
6424 }
6425
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006426 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006427 // If the application handles the original key for which we previously
6428 // generated a fallback or if the window is not a foreground window,
6429 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006430 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006431 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006432 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6433 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6434 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6435 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6436 keyEntry.policyFlags);
6437 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006438 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006439 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440
6441 mLock.unlock();
6442
Prabir Pradhana41d2442023-04-20 21:30:40 +00006443 if (const auto unhandledKeyFallback =
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006444 mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6445 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006446 unhandledKeyFallback) {
6447 event = *unhandledKeyFallback;
6448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006449
6450 mLock.lock();
6451
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006452 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006453 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006454 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006455 "application handled the original non-fallback key "
6456 "or is no longer a foreground target, "
6457 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 connection->inputState.removeFallbackKey(originalKeyCode);
6462 }
6463 } else {
6464 // If the application did not handle a non-fallback key, first check
6465 // that we are in a good state to perform unhandled key event processing
6466 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006467 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006468 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006469 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6470 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6471 "since this is not an initial down. "
6472 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6473 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6474 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006475 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006477
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006478 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006479 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6480 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6481 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6482 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6483 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006484 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485
6486 mLock.unlock();
6487
Prabir Pradhana41d2442023-04-20 21:30:40 +00006488 bool fallback = false;
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006489 if (auto fb = mPolicy.dispatchUnhandledKey(connection->getToken(), event,
6490 keyEntry.policyFlags);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006491 fb) {
6492 fallback = true;
6493 event = *fb;
6494 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006495
6496 mLock.lock();
6497
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006498 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006499 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006500 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006501 }
6502
6503 // Latch the fallback keycode for this key on an initial down.
6504 // The fallback keycode cannot change at any other point in the lifecycle.
6505 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006507 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006509 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006510 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006511 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006512 }
6513
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006514 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006515
6516 // Cancel the fallback key if the policy decides not to send it anymore.
6517 // We will continue to dispatch the key to the policy but we will no
6518 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006519 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6520 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006521 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6522 if (fallback) {
6523 ALOGD("Unhandled key event: Policy requested to send key %d"
6524 "as a fallback for %d, but on the DOWN it had requested "
6525 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006526 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 } else {
6528 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6529 "but on the DOWN it had requested to send %d. "
6530 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006531 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006532 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006533 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006534
Michael Wrightfb04fd52022-11-24 22:31:11 +00006535 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006536 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006537 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006538 synthesizeCancelationEventsForConnectionLocked(connection, options);
6539
6540 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006541 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006542 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006543 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006544 }
6545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006546
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006547 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6548 {
6549 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006550 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006551 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006552 for (const auto& [key, value] : fallbackKeys) {
6553 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006554 }
6555 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6556 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006558 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006559
6560 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006561 // Return the fallback key that we want dispatched to the channel.
6562 std::unique_ptr<KeyEntry> newEntry =
6563 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6564 event.getEventTime(), event.getDeviceId(),
6565 event.getSource(), event.getDisplayId(),
6566 keyEntry.policyFlags, keyEntry.action,
6567 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6568 *fallbackKeyCode, event.getScanCode(),
6569 event.getMetaState(), event.getRepeatCount(),
6570 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006571 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6572 ALOGD("Unhandled key event: Dispatching fallback key. "
6573 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006574 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006575 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006576 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006577 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006578 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6579 ALOGD("Unhandled key event: No fallback key.");
6580 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006581
6582 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006583 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584 }
6585 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006586 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587}
6588
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589void InputDispatcher::traceInboundQueueLengthLocked() {
6590 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006591 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 }
6593}
6594
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006595void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006596 if (ATRACE_ENABLED()) {
6597 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006598 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6599 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600 }
6601}
6602
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006603void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 if (ATRACE_ENABLED()) {
6605 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006606 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6607 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 }
6609}
6610
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006611void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006612 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006614 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 dumpDispatchStateLocked(dump);
6616
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006617 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006618 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006619 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620 }
6621}
6622
6623void InputDispatcher::monitor() {
6624 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006625 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006626 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006627 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628}
6629
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006630/**
6631 * Wake up the dispatcher and wait until it processes all events and commands.
6632 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6633 * this method can be safely called from any thread, as long as you've ensured that
6634 * the work you are interested in completing has already been queued.
6635 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006636bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006637 /**
6638 * Timeout should represent the longest possible time that a device might spend processing
6639 * events and commands.
6640 */
6641 constexpr std::chrono::duration TIMEOUT = 100ms;
6642 std::unique_lock lock(mLock);
6643 mLooper->wake();
6644 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6645 return result == std::cv_status::no_timeout;
6646}
6647
Vishnu Naire798b472020-07-23 13:52:21 -07006648/**
6649 * Sets focus to the window identified by the token. This must be called
6650 * after updating any input window handles.
6651 *
6652 * Params:
6653 * request.token - input channel token used to identify the window that should gain focus.
6654 * request.focusedToken - the token that the caller expects currently to be focused. If the
6655 * specified token does not match the currently focused window, this request will be dropped.
6656 * If the specified focused token matches the currently focused window, the call will succeed.
6657 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6658 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6659 * when requesting the focus change. This determines which request gets
6660 * precedence if there is a focus change request from another source such as pointer down.
6661 */
Vishnu Nair958da932020-08-21 17:12:37 -07006662void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6663 { // acquire lock
6664 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006665 std::optional<FocusResolver::FocusChanges> changes =
6666 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6667 if (changes) {
6668 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006669 }
6670 } // release lock
6671 // Wake up poll loop since it may need to make new input dispatching choices.
6672 mLooper->wake();
6673}
6674
Vishnu Nairc519ff72021-01-21 08:23:08 -08006675void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6676 if (changes.oldFocus) {
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006677 std::shared_ptr<Connection> focusedConnection = getConnectionLocked(changes.oldFocus);
6678 if (focusedConnection) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006679 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006680 "focus left window");
Siarhei Vishniakou18cbdb82024-01-31 17:58:13 -08006681 synthesizeCancelationEventsForConnectionLocked(focusedConnection, options);
Harry Cutts33476232023-01-30 19:57:29 +00006682 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006683 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006684 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006685 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006686 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006687 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006688 }
6689
Prabir Pradhan99987712020-11-10 18:43:05 -08006690 // If a window has pointer capture, then it must have focus. We need to ensure that this
6691 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6692 // If the window loses focus before it loses pointer capture, then the window can be in a state
6693 // where it has pointer capture but not focus, violating the contract. Therefore we must
6694 // dispatch the pointer capture event before the focus event. Since focus events are added to
6695 // the front of the queue (above), we add the pointer capture event to the front of the queue
6696 // after the focus events are added. This ensures the pointer capture event ends up at the
6697 // front.
6698 disablePointerCaptureForcedLocked();
6699
Vishnu Nairc519ff72021-01-21 08:23:08 -08006700 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006701 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006702 }
6703}
Vishnu Nair958da932020-08-21 17:12:37 -07006704
Prabir Pradhan99987712020-11-10 18:43:05 -08006705void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006706 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006707 return;
6708 }
6709
6710 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6711
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006712 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006713 setPointerCaptureLocked(false);
6714 }
6715
6716 if (!mWindowTokenWithPointerCapture) {
6717 // No need to send capture changes because no window has capture.
6718 return;
6719 }
6720
6721 if (mPendingEvent != nullptr) {
6722 // Move the pending event to the front of the queue. This will give the chance
6723 // for the pending event to be dropped if it is a captured event.
6724 mInboundQueue.push_front(mPendingEvent);
6725 mPendingEvent = nullptr;
6726 }
6727
6728 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006729 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006730 mInboundQueue.push_front(std::move(entry));
6731}
6732
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006733void InputDispatcher::setPointerCaptureLocked(bool enable) {
6734 mCurrentPointerCaptureRequest.enable = enable;
6735 mCurrentPointerCaptureRequest.seq++;
6736 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006737 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006738 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006739 };
6740 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006741}
6742
Vishnu Nair599f1412021-06-21 10:39:58 -07006743void InputDispatcher::displayRemoved(int32_t displayId) {
6744 { // acquire lock
6745 std::scoped_lock _l(mLock);
6746 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006747 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006748 setFocusedApplicationLocked(displayId, nullptr);
6749 // Call focus resolver to clean up stale requests. This must be called after input windows
6750 // have been removed for the removed display.
6751 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006752 // Reset pointer capture eligibility, regardless of previous state.
6753 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006754 // Remove the associated touch mode state.
6755 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006756 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006757 } // release lock
6758
6759 // Wake up poll loop since it may need to make new input dispatching choices.
6760 mLooper->wake();
6761}
6762
Patrick Williamsd828f302023-04-28 17:52:08 -05006763void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006764 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6765 {
6766 // acquire lock
6767 std::scoped_lock _l(mLock);
6768 logDispatchStateLocked();
6769 }
6770 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6771 result.error().message().c_str());
6772 };
chaviw15fab6f2021-06-07 14:15:52 -05006773 // The listener sends the windows as a flattened array. Separate the windows by display for
6774 // more convenient parsing.
6775 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006776 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006777 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006778 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006779 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006780
6781 { // acquire lock
6782 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006783
6784 // Ensure that we have an entry created for all existing displays so that if a displayId has
6785 // no windows, we can tell that the windows were removed from the display.
6786 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6787 handlesPerDisplay[displayId];
6788 }
6789
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006790 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006791 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006792 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6793 }
6794
6795 for (const auto& [displayId, handles] : handlesPerDisplay) {
6796 setInputWindowsLocked(handles, displayId);
6797 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006798
6799 if (update.vsyncId < mWindowInfosVsyncId) {
6800 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6801 ", current update vsync id: %" PRId64,
6802 mWindowInfosVsyncId, update.vsyncId);
6803 }
6804 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006805 }
6806 // Wake up poll loop since it may need to make new input dispatching choices.
6807 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006808}
6809
Vishnu Nair062a8672021-09-03 16:07:44 -07006810bool InputDispatcher::shouldDropInput(
6811 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006812 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6813 (windowHandle->getInfo()->inputConfig.test(
6814 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006815 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006816 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6817 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006818 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006819 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006820 windowHandle->getInfo()->displayId);
6821 return true;
6822 }
6823 return false;
6824}
6825
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006826void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006827 const gui::WindowInfosUpdate& update) {
6828 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006829}
6830
Arthur Hungdfd528e2021-12-08 13:23:04 +00006831void InputDispatcher::cancelCurrentTouch() {
6832 {
6833 std::scoped_lock _l(mLock);
6834 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006835 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006836 "cancel current touch");
6837 synthesizeCancelationEventsForAllConnectionsLocked(options);
6838
6839 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006840 }
6841 // Wake up poll loop since there might be work to do.
6842 mLooper->wake();
6843}
6844
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006845void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6846 std::scoped_lock _l(mLock);
6847 mMonitorDispatchingTimeout = timeout;
6848}
6849
Arthur Hungc539dbb2022-12-08 07:45:36 +00006850void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6851 const sp<WindowInfoHandle>& oldWindowHandle,
6852 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006853 TouchState& state, int32_t deviceId,
6854 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006855 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006856 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006857 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6858 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6859 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6860 newWindowHandle->getInfo()->inputConfig.test(
6861 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6862 const sp<WindowInfoHandle> oldWallpaper =
6863 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6864 const sp<WindowInfoHandle> newWallpaper =
6865 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6866 if (oldWallpaper == newWallpaper) {
6867 return;
6868 }
6869
6870 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006871 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006872 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006873 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006874 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006875 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006876 }
6877
6878 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006879 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6880 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006881 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006882 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006883 }
6884}
6885
6886void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6887 ftl::Flags<InputTarget::Flags> newTargetFlags,
6888 const sp<WindowInfoHandle> fromWindowHandle,
6889 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006890 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006891 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006892 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6893 fromWindowHandle->getInfo()->inputConfig.test(
6894 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6895 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6896 toWindowHandle->getInfo()->inputConfig.test(
6897 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6898
6899 const sp<WindowInfoHandle> oldWallpaper =
6900 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6901 const sp<WindowInfoHandle> newWallpaper =
6902 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6903 if (oldWallpaper == newWallpaper) {
6904 return;
6905 }
6906
6907 if (oldWallpaper != nullptr) {
6908 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6909 "transferring touch focus to another window");
6910 state.removeWindowByToken(oldWallpaper->getToken());
6911 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6912 }
6913
6914 if (newWallpaper != nullptr) {
6915 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006916 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006917 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6918 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006919 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006920 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006921 std::shared_ptr<Connection> wallpaperConnection =
6922 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006923 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006924 std::shared_ptr<Connection> toConnection =
6925 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006926 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6927 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6928 wallpaperFlags);
6929 }
6930 }
6931}
6932
6933sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6934 const sp<WindowInfoHandle>& windowHandle) const {
6935 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6936 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6937 bool foundWindow = false;
6938 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6939 if (!foundWindow && otherHandle != windowHandle) {
6940 continue;
6941 }
6942 if (windowHandle == otherHandle) {
6943 foundWindow = true;
6944 continue;
6945 }
6946
6947 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6948 return otherHandle;
6949 }
6950 }
6951 return nullptr;
6952}
6953
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006954void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6955 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006956 std::scoped_lock _l(mLock);
6957
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006958 mConfig.keyRepeatTimeout = timeout.count();
6959 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006960}
6961
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006962bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6963 DeviceId deviceId, int32_t pointerId) {
6964 std::scoped_lock _l(mLock);
6965 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
6966 if (touchStateIt == mTouchStatesByDisplay.end()) {
6967 return false;
6968 }
6969 for (const TouchedWindow& window : touchStateIt->second.windows) {
6970 if (window.windowHandle->getToken() == token &&
6971 (window.hasTouchingPointer(deviceId, pointerId) ||
6972 window.hasHoveringPointer(deviceId, pointerId))) {
6973 return true;
6974 }
6975 }
6976 return false;
6977}
6978
Garfield Tane84e6f92019-08-29 17:28:41 -07006979} // namespace android::inputdispatcher