blob: da3b032d8258e57ce2b8f17c778d1dab1d3e521f [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Prabir Pradhanadc59b42023-12-15 05:34:11 +000038#include <private/android_filesystem_config.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000055#include "trace/InputTracer.h"
56#include "trace/InputTracingPerfettoBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010057
Michael Wrightd02c5b62014-02-10 15:10:22 -080058#define INDENT " "
59#define INDENT2 " "
60#define INDENT3 " "
61#define INDENT4 " "
62
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080063using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070064using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080065using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000066using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070068using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050069using android::gui::FocusRequest;
70using android::gui::TouchOcclusionMode;
71using android::gui::WindowInfo;
72using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080073using android::os::InputEventInjectionResult;
74using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000075namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
Prabir Pradhancef936d2021-07-21 16:17:52 +000079namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000080
Prabir Pradhandae52792023-12-15 07:36:40 +000081// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
82// flag is enabled. When the flag is changed, tracing will only be available after reboot.
83bool isInputTracingEnabled() {
84 static const std::string buildType = base::GetProperty("ro.build.type", "user");
85 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
86 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
87}
88
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000089template <class Entry>
90void ensureEventTraced(const Entry& entry) {
91 if (!entry.traceTracker) {
92 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
93 }
94}
95
Prabir Pradhancef936d2021-07-21 16:17:52 +000096// Temporarily releases a held mutex for the lifetime of the instance.
97// Named to match std::scoped_lock
98class scoped_unlock {
99public:
100 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
101 ~scoped_unlock() { mMutex.lock(); }
102
103private:
104 std::mutex& mMutex;
105};
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Default input dispatching timeout if there is no focused application or paused window
108// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800109const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
110 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
111 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800113// The default minimum time gap between two user activity poke events.
114const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
115
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800116const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
120
121// Log a warning when an interception call takes longer than this to process.
122constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700124// Additional key latency in case a connection is still processing some motion events.
125// This will help with the case when a user touched a button that opens a new window,
126// and gives us the chance to dispatch the key to this new window.
127constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000130constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
131
Antonio Kantekea47acb2021-12-23 12:41:25 -0800132// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000133constexpr int LOGTAG_INPUT_INTERACTION = 62000;
134constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000135constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000136
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000137const ui::Transform kIdentityTransform;
138
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000139inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 return systemTime(SYSTEM_TIME_MONOTONIC);
141}
142
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700143inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000144 if (binder == nullptr) {
145 return "<null>";
146 }
147 return StringPrintf("%p", binder.get());
148}
149
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000150static std::string uidString(const gui::Uid& uid) {
151 return uid.toString();
152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AKEY_EVENT_ACTION_DOWN:
157 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700158 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700159 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700160 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 }
162}
163
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700164Result<void> validateKeyEvent(int32_t action) {
165 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166}
167
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800169 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700171 case AMOTION_EVENT_ACTION_UP: {
172 if (pointerCount != 1) {
173 return Error() << "invalid pointer count " << pointerCount;
174 }
175 return {};
176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_HOVER_ENTER:
179 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700180 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
181 if (pointerCount < 1) {
182 return Error() << "invalid pointer count " << pointerCount;
183 }
184 return {};
185 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800186 case AMOTION_EVENT_ACTION_CANCEL:
187 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700189 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 case AMOTION_EVENT_ACTION_POINTER_DOWN:
191 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800192 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193 if (index < 0) {
194 return Error() << "invalid index " << index << " for "
195 << MotionEvent::actionToString(action);
196 }
197 if (index >= pointerCount) {
198 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
199 }
200 if (pointerCount <= 1) {
201 return Error() << "invalid pointer count " << pointerCount << " for "
202 << MotionEvent::actionToString(action);
203 }
204 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700205 }
206 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700207 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
208 if (actionButton == 0) {
209 return Error() << "action button should be nonzero for "
210 << MotionEvent::actionToString(action);
211 }
212 return {};
213 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700215 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217}
218
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000219int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500220 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
221}
222
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
224 const PointerProperties* pointerProperties) {
225 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
226 if (!actionCheck.ok()) {
227 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
229 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700230 return Error() << "Motion event has invalid pointer count " << pointerCount
231 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800233 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 for (size_t i = 0; i < pointerCount; i++) {
235 int32_t id = pointerProperties[i].id;
236 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700237 return Error() << "Motion event has invalid pointer id " << id
238 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800240 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700241 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800243 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700245 return {};
246}
247
248Result<void> validateInputEvent(const InputEvent& event) {
249 switch (event.getType()) {
250 case InputEventType::KEY: {
251 const KeyEvent& key = static_cast<const KeyEvent&>(event);
252 const int32_t action = key.getAction();
253 return validateKeyEvent(action);
254 }
255 case InputEventType::MOTION: {
256 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
257 const int32_t action = motion.getAction();
258 const size_t pointerCount = motion.getPointerCount();
259 const PointerProperties* pointerProperties = motion.getPointerProperties();
260 const int32_t actionButton = motion.getActionButton();
261 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
262 }
263 default: {
264 return {};
265 }
266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267}
268
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800269std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
270 std::bitset<MAX_POINTER_ID + 1> pointerIds;
271 for (const PointerProperties& pointer : pointers) {
272 pointerIds.set(pointer.id);
273 }
274 return pointerIds;
275}
276
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000277std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000279 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 }
281
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000282 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 bool first = true;
284 Region::const_iterator cur = region.begin();
285 Region::const_iterator const tail = region.end();
286 while (cur != tail) {
287 if (first) {
288 first = false;
289 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800290 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800292 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800293 cur++;
294 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000295 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296}
297
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000298std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
299 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500300 constexpr size_t maxEntries = 50; // max events to print
301 constexpr size_t skipBegin = maxEntries / 2;
302 const size_t skipEnd = queue.size() - maxEntries / 2;
303 // skip from maxEntries / 2 ... size() - maxEntries/2
304 // only print from 0 .. skipBegin and then from skipEnd .. size()
305
306 std::string dump;
307 for (size_t i = 0; i < queue.size(); i++) {
308 const DispatchEntry& entry = *queue[i];
309 if (i >= skipBegin && i < skipEnd) {
310 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
311 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
312 continue;
313 }
314 dump.append(INDENT4);
315 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000316 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
317 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500318 ns2ms(currentTime - entry.eventEntry->eventTime));
319 if (entry.deliveryTime != 0) {
320 // This entry was delivered, so add information on how long we've been waiting
321 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
322 }
323 dump.append("\n");
324 }
325 return dump;
326}
327
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700328/**
329 * Find the entry in std::unordered_map by key, and return it.
330 * If the entry is not found, return a default constructed entry.
331 *
332 * Useful when the entries are vectors, since an empty vector will be returned
333 * if the entry is not found.
334 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
335 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700336template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700338 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700339 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800340}
341
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700343 if (first == second) {
344 return true;
345 }
346
347 if (first == nullptr || second == nullptr) {
348 return false;
349 }
350
351 return first->getToken() == second->getToken();
352}
353
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000354bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000355 if (first == nullptr || second == nullptr) {
356 return false;
357 }
358 return first->applicationInfo.token != nullptr &&
359 first->applicationInfo.token == second->applicationInfo.token;
360}
361
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800362template <typename T>
363size_t firstMarkedBit(T set) {
364 // TODO: replace with std::countr_zero from <bit> when that's available
365 LOG_ALWAYS_FATAL_IF(set.none());
366 size_t i = 0;
367 while (!set.test(i)) {
368 i++;
369 }
370 return i;
371}
372
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000373std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
374 std::shared_ptr<const EventEntry> eventEntry,
375 ftl::Flags<InputTarget::Flags> inputTargetFlags,
376 int64_t vsyncId) {
377 const sp<WindowInfoHandle> win = inputTarget.windowHandle;
378 const std::optional<int32_t> windowId =
379 win ? std::make_optional(win->getInfo()->id) : std::nullopt;
380 // Assume the only targets that are not associated with a window are global monitors, and use
381 // the system UID for global monitors for tracing purposes.
382 const gui::Uid uid = win ? win->getInfo()->ownerUid : gui::Uid(AID_SYSTEM);
chaviw1ff3d1e2020-07-01 15:53:47 -0700383 if (inputTarget.useDefaultPointerTransform()) {
384 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700385 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700386 inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000387 inputTarget.globalScaleFactor, uid, vsyncId,
388 windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 }
390
391 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
392 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700395 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000396
397 // Use the first pointer information to normalize all other pointers. This could be any pointer
398 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700399 // uses the transform for the normalized pointer.
400 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800401 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700402 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700405 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000406 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
407 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700408 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000409
410 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700411 // First, apply the current pointer's transform to update the coordinates into
412 // window space.
413 pointerCoords[pointerIndex].transform(currTransform);
414 // Next, apply the inverse transform of the normalized coordinates so the
415 // current coordinates are transformed into the normalized coordinate space.
416 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000417 }
418
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700419 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000420 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
421 motionEntry.eventTime, motionEntry.deviceId,
422 motionEntry.source, motionEntry.displayId,
423 motionEntry.policyFlags, motionEntry.action,
424 motionEntry.actionButton, motionEntry.flags,
425 motionEntry.metaState, motionEntry.buttonState,
426 motionEntry.classification, motionEntry.edgeFlags,
427 motionEntry.xPrecision, motionEntry.yPrecision,
428 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
429 motionEntry.downTime, motionEntry.pointerProperties,
430 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431
432 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700433 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700434 firstPointerTransform, inputTarget.displayTransform,
Prabir Pradhanadc59b42023-12-15 05:34:11 +0000435 inputTarget.globalScaleFactor, uid, vsyncId, windowId);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000436 return dispatchEntry;
437}
438
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
440 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700441 std::unique_ptr<InputChannel> uniqueServerChannel;
442 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
443
444 serverChannel = std::move(uniqueServerChannel);
445 return result;
446}
447
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500448template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000449bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500450 if (lhs == nullptr && rhs == nullptr) {
451 return true;
452 }
453 if (lhs == nullptr || rhs == nullptr) {
454 return false;
455 }
456 return *lhs == *rhs;
457}
458
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000459KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000460 KeyEvent event;
461 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
462 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
463 entry.repeatCount, entry.downTime, entry.eventTime);
464 return event;
465}
466
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000467bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 // Do not keep track of gesture monitors. They receive every event and would disproportionately
469 // affect the statistics.
470 if (connection.monitor) {
471 return false;
472 }
473 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
474 if (!connection.responsive) {
475 return false;
476 }
477 return true;
478}
479
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000480bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000481 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
482 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000483 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
484 return false;
485 }
486 // Only track latency for events that originated from hardware
487 if (eventEntry.isSynthesized()) {
488 return false;
489 }
490 const EventEntry::Type& inputEventEntryType = eventEntry.type;
491 if (inputEventEntryType == EventEntry::Type::KEY) {
492 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
493 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
494 return false;
495 }
496 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
497 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
498 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
499 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
500 return false;
501 }
502 } else {
503 // Not a key or a motion
504 return false;
505 }
506 if (!shouldReportMetricsForConnection(connection)) {
507 return false;
508 }
509 return true;
510}
511
Prabir Pradhancef936d2021-07-21 16:17:52 +0000512/**
513 * Connection is responsive if it has no events in the waitQueue that are older than the
514 * current time.
515 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000516bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000517 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000518 for (const auto& dispatchEntry : connection.waitQueue) {
519 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000520 return false;
521 }
522 }
523 return true;
524}
525
Antonio Kantekf16f2832021-09-28 04:39:20 +0000526// Returns true if the event type passed as argument represents a user activity.
527bool isUserActivityEvent(const EventEntry& eventEntry) {
528 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000529 case EventEntry::Type::CONFIGURATION_CHANGED:
530 case EventEntry::Type::DEVICE_RESET:
531 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000532 case EventEntry::Type::FOCUS:
533 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000534 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000535 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000536 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000537 case EventEntry::Type::KEY:
538 case EventEntry::Type::MOTION:
539 return true;
540 }
541}
542
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800543// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000544bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000545 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800546 const auto inputConfig = windowInfo.inputConfig;
547 if (windowInfo.displayId != displayId ||
548 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800549 return false;
550 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800552 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800553 return false;
554 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000555
556 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
557 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
558 // the window. Points on the right and bottom edges should not be inside the window, so we need
559 // to be careful about performing a hit test when the display is rotated, since the "right" and
560 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
561 // logical display in which WM determined the bounds. Perform the hit test in the logical
562 // display space to ensure these edges are considered correctly in all orientations.
563 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
564 const auto p = displayTransform.transform(x, y);
565 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800566 return false;
567 }
568 return true;
569}
570
Prabir Pradhand65552b2021-10-07 11:23:50 -0700571bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
572 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000573 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700574}
575
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800576// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000577// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
578// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
579// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800580// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000581bool canReceiveForegroundTouches(const WindowInfo& info) {
582 // A non-touchable window can still receive touch events (e.g. in the case of
583 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
584 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
585}
586
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000587bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700588 if (windowHandle == nullptr) {
589 return false;
590 }
591 const WindowInfo* windowInfo = windowHandle->getInfo();
592 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
593 return true;
594 }
595 return false;
596}
597
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598// Checks targeted injection using the window's owner's uid.
599// Returns an empty string if an entry can be sent to the given window, or an error message if the
600// entry is a targeted injection whose uid target doesn't match the window owner.
601std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
602 const EventEntry& entry) {
603 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
604 // The event was not injected, or the injected event does not target a window.
605 return {};
606 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000607 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000608 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000609 return StringPrintf("No valid window target for injection into uid %s.",
610 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000611 }
612 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000613 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
614 "owned by uid %s.",
615 uid.toString().c_str(), window->getName().c_str(),
616 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000617 }
618 return {};
619}
620
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000621std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700622 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
623 // Always dispatch mouse events to cursor position.
624 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000625 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700626 }
627
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700628 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000629 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
630 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700631}
632
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700633std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
634 if (eventEntry.type == EventEntry::Type::KEY) {
635 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
636 return keyEntry.downTime;
637 } else if (eventEntry.type == EventEntry::Type::MOTION) {
638 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
639 return motionEntry.downTime;
640 }
641 return std::nullopt;
642}
643
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000644/**
645 * Compare the old touch state to the new touch state, and generate the corresponding touched
646 * windows (== input targets).
647 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
648 * If the pointer just entered the new window, produce HOVER_ENTER.
649 * For pointers remaining in the window, produce HOVER_MOVE.
650 */
651std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
652 const TouchState& newTouchState,
653 const MotionEntry& entry) {
654 std::vector<TouchedWindow> out;
655 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700656
657 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
658 // ACTION_SCROLL events should not affect the hovering pointer dispatch
659 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 }
661
662 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800663 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000664
665 std::set<sp<WindowInfoHandle>> oldWindows;
666 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800667 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000668 }
669
670 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800671 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000672
673 // If the pointer is no longer in the new window set, send HOVER_EXIT.
674 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
675 if (newWindows.find(oldWindow) == newWindows.end()) {
676 TouchedWindow touchedWindow;
677 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000678 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000679 out.push_back(touchedWindow);
680 }
681 }
682
683 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
684 TouchedWindow touchedWindow;
685 touchedWindow.windowHandle = newWindow;
686 if (oldWindows.find(newWindow) == oldWindows.end()) {
687 // Any windows that have this pointer now, and didn't have it before, should get
688 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000689 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000690 } else {
691 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700692 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700693 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000694 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
695 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700696 // The Accessibility injected touch exploration event stream
697 // has known inconsistencies, so log ERROR instead of
698 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700699 severity = android::base::LogSeverity::ERROR;
700 }
701 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700702 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000703 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000704 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800705 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000706 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
707 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
708 }
709 out.push_back(touchedWindow);
710 }
711 return out;
712}
713
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800714template <typename T>
715std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
716 left.insert(left.end(), right.begin(), right.end());
717 return left;
718}
719
Harry Cuttsb166c002023-05-09 13:06:05 +0000720// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
721// both.
722void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
723 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
724 if (!window.windowHandle->getInfo()->inputConfig.test(
725 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
726 // In addition to TouchState, erase this window from the input targets! We don't have a
727 // good way to do this today except by adding a nested loop.
728 // TODO(b/282025641): simplify this code once InputTargets are being identified
729 // separately from TouchedWindows.
730 std::erase_if(targets, [&](const InputTarget& target) {
731 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
732 });
733 return true;
734 }
735 return false;
736 });
737}
738
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700739/**
740 * In general, touch should be always split between windows. Some exceptions:
741 * 1. Don't split touch if all of the below is true:
742 * (a) we have an active pointer down *and*
743 * (b) a new pointer is going down that's from the same device *and*
744 * (c) the window that's receiving the current pointer does not support split touch.
745 * 2. Don't split mouse events
746 */
747bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
748 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
749 // We should never split mouse events
750 return false;
751 }
752 for (const TouchedWindow& touchedWindow : touchState.windows) {
753 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
754 // Spy windows should not affect whether or not touch is split.
755 continue;
756 }
757 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
758 continue;
759 }
760 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
761 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
762 // Wallpaper window should not affect whether or not touch is split
763 continue;
764 }
765
766 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
767 return false;
768 }
769 }
770 return true;
771}
772
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700773/**
774 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
775 */
776bool isStylusActiveInDisplay(
777 int32_t displayId,
778 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
779 const auto it = touchStatesByDisplay.find(displayId);
780 if (it == touchStatesByDisplay.end()) {
781 return false;
782 }
783 const TouchState& state = it->second;
784 return state.hasActiveStylus();
785}
786
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800787Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
788 struct HashFunction {
789 size_t operator()(const WindowInfo& info) const { return info.id; }
790 };
791
792 std::unordered_set<WindowInfo, HashFunction> windowSet;
793 for (const WindowInfo& info : update.windowInfos) {
794 const auto [_, inserted] = windowSet.insert(info);
795 if (!inserted) {
796 return Error() << "Duplicate entry for " << info;
797 }
798 }
799 return {};
800}
801
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800802int32_t getUserActivityEventType(const EventEntry& eventEntry) {
803 switch (eventEntry.type) {
804 case EventEntry::Type::KEY: {
805 return USER_ACTIVITY_EVENT_BUTTON;
806 }
807 case EventEntry::Type::MOTION: {
808 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
809 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
810 return USER_ACTIVITY_EVENT_TOUCH;
811 }
812 return USER_ACTIVITY_EVENT_OTHER;
813 }
814 default: {
815 LOG_ALWAYS_FATAL("%s events are not user activity",
816 ftl::enum_string(eventEntry.type).c_str());
817 }
818 }
819}
820
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000821} // namespace
822
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823// --- InputDispatcher ---
824
Prabir Pradhana41d2442023-04-20 21:30:40 +0000825InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000826 : InputDispatcher(policy,
827 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
828 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000829
830InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
831 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700832 : mPolicy(policy),
833 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800835 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800836 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700837 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800838 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700839 mDispatchEnabled(false),
840 mDispatchFrozen(false),
841 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100842 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000843 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800844 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000845 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000846 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700847 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800848 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700850 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700851#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700852 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700853#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700854 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000855
856 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000857 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000858 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800859
860 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861}
862
863InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
Prabir Pradhancef936d2021-07-21 16:17:52 +0000866 resetKeyRepeatLocked();
867 releasePendingEventLocked();
868 drainInboundQueueLocked();
869 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000871 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700872 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000873 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875}
876
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700877status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700878 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700879 return ALREADY_EXISTS;
880 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700881 mThread = std::make_unique<InputThread>(
882 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
883 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700884}
885
886status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700887 if (mThread && mThread->isCallingThread()) {
888 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700889 return INVALID_OPERATION;
890 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700891 mThread.reset();
892 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700896 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800898 std::scoped_lock _l(mLock);
899 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 // Run a dispatch loop if there are no pending commands.
902 // The dispatch loop might enqueue commands to run afterwards.
903 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800904 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 // Run all pending commands if there are any.
908 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000909 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700910 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913 // If we are still waiting for ack on some events,
914 // we might have to wake up earlier to check if an app is anr'ing.
915 const nsecs_t nextAnrCheck = processAnrsLocked();
916 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
917
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800918 // We are about to enter an infinitely long sleep, because we have no commands or
919 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700920 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800921 mDispatcherEnteredIdle.notify_all();
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 } // release lock
924
925 // Wait for callback or timeout or wake. (make sure we round up, not down)
926 nsecs_t currentTime = now();
927 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
928 mLooper->pollOnce(timeoutMillis);
929}
930
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500932 * Raise ANR if there is no focused window.
933 * Before the ANR is raised, do a final state check:
934 * 1. The currently focused application must be the same one we are waiting for.
935 * 2. Ensure we still don't have a focused window.
936 */
937void InputDispatcher::processNoFocusedWindowAnrLocked() {
938 // Check if the application that we are waiting for is still focused.
939 std::shared_ptr<InputApplicationHandle> focusedApplication =
940 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
941 if (focusedApplication == nullptr ||
942 focusedApplication->getApplicationToken() !=
943 mAwaitedFocusedApplication->getApplicationToken()) {
944 // Unexpected because we should have reset the ANR timer when focused application changed
945 ALOGE("Waited for a focused window, but focused application has already changed to %s",
946 focusedApplication->getName().c_str());
947 return; // The focused application has changed.
948 }
949
chaviw98318de2021-05-19 16:45:23 -0500950 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500951 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
952 if (focusedWindowHandle != nullptr) {
953 return; // We now have a focused window. No need for ANR.
954 }
955 onAnrLocked(mAwaitedFocusedApplication);
956}
957
958/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 * Check if any of the connections' wait queues have events that are too old.
960 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
961 * Return the time at which we should wake up next.
962 */
963nsecs_t InputDispatcher::processAnrsLocked() {
964 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700965 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
967 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
968 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500969 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700970 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500971 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700972 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500974 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
976 }
977 }
978
979 // Check if any connection ANRs are due
980 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
981 if (currentTime < nextAnrCheck) { // most likely scenario
982 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
983 }
984
985 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700986 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700987 if (connection == nullptr) {
988 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
989 return nextAnrCheck;
990 }
991 connection->responsive = false;
992 // Stop waking up for this unresponsive connection
993 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000994 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700995 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996}
997
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800998std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700999 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08001000 if (connection->monitor) {
1001 return mMonitorDispatchingTimeout;
1002 }
1003 const sp<WindowInfoHandle> window =
1004 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001005 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001006 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001007 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001008 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001009}
1010
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001011void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 nsecs_t currentTime = now();
1013
Jeff Browndc5992e2014-04-11 01:27:26 -07001014 // Reset the key repeat timer whenever normal dispatch is suspended while the
1015 // device is in a non-interactive state. This is to ensure that we abort a key
1016 // repeat if the device is just coming out of sleep.
1017 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 resetKeyRepeatLocked();
1019 }
1020
1021 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1022 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001023 if (DEBUG_FOCUS) {
1024 ALOGD("Dispatch frozen. Waiting some more.");
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 return;
1027 }
1028
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 // Ready to start a new event.
1030 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 // Synthesize a key repeat if appropriate.
1034 if (mKeyRepeatState.lastKeyEntry) {
1035 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1036 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1037 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001038 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040 }
1041
1042 // Nothing to do if there is no pending event.
1043 if (!mPendingEvent) {
1044 return;
1045 }
1046 } else {
1047 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001048 mPendingEvent = mInboundQueue.front();
1049 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 traceInboundQueueLengthLocked();
1051 }
1052
1053 // Poke user activity for this event.
1054 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001055 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058
1059 // Now we have an event to dispatch.
1060 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001065 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001067 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069
1070 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001071 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
1073
1074 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 const ConfigurationChangedEntry& typedEntry =
1077 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 break;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001083 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 const DeviceResetEntry& typedEntry =
1085 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 break;
1089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001091 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001092 std::shared_ptr<const FocusEntry> typedEntry =
1093 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001094 dispatchFocusLocked(currentTime, typedEntry);
1095 done = true;
1096 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1097 break;
1098 }
1099
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001100 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001101 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001102 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1103 done = true;
1104 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1105 break;
1106 }
1107
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1109 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001110 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001111 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1112 done = true;
1113 break;
1114 }
1115
arthurhungb89ccb02020-12-30 16:19:01 +08001116 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001117 std::shared_ptr<const DragEntry> typedEntry =
1118 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001119 dispatchDragLocked(currentTime, typedEntry);
1120 done = true;
1121 break;
1122 }
1123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001125 std::shared_ptr<const KeyEntry> keyEntry =
1126 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1131 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001133 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001134 if (done && mTracer) {
1135 ensureEventTraced(*keyEntry);
1136 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 break;
1139 }
1140
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001141 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001142 std::shared_ptr<const MotionEntry> motionEntry =
1143 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001144 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001145 // The event is stale. However, only drop stale events if there isn't an ongoing
1146 // gesture. That would allow us to complete the processing of the current stroke.
1147 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1148 if (touchStateIt != mTouchStatesByDisplay.end()) {
1149 const TouchState& touchState = touchStateIt->second;
1150 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1151 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1152 dropReason = DropReason::STALE;
1153 }
1154 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001157 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1158 // Only drop events that are focus-dispatched.
1159 dropReason = DropReason::BLOCKED;
1160 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001163 if (done && mTracer) {
1164 ensureEventTraced(*motionEntry);
1165 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
Chris Yef59a2f42020-10-16 12:55:26 -07001169
1170 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001171 std::shared_ptr<const SensorEntry> sensorEntry =
1172 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001173
Chris Yef59a2f42020-10-16 12:55:26 -07001174 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1175 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1176 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1177 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1178 dropReason = DropReason::STALE;
1179 }
1180 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1181 done = true;
1182 break;
1183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
1185
1186 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
Michael Wright3a981722015-06-10 15:26:13 +01001190 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191
1192 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001193 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195}
1196
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001197bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001198 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001199}
1200
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001201/**
1202 * Return true if the events preceding this incoming motion event should be dropped
1203 * Return false otherwise (the default behaviour)
1204 */
1205bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001207 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001208
1209 // Optimize case where the current application is unresponsive and the user
1210 // decides to touch a window in a different application.
1211 // If the application takes too long to catch up then we drop all events preceding
1212 // the touch into the other window.
1213 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001214 const int32_t displayId = motionEntry.displayId;
1215 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001216 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001217
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001218 sp<WindowInfoHandle> touchedWindowHandle =
1219 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001220 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001221 touchedWindowHandle->getApplicationToken() !=
1222 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001223 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 ALOGI("Pruning input queue because user touched a different application while waiting "
1225 "for %s",
1226 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001227 return true;
1228 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001229
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001230 // Alternatively, maybe there's a spy window that could handle this event.
1231 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1232 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1233 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001234 const std::shared_ptr<Connection> connection =
1235 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001236 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001237 // This spy window could take more input. Drop all events preceding this
1238 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001239 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001240 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001241 mAwaitedFocusedApplication->getName().c_str());
1242 return true;
1243 }
1244 }
1245 }
1246
1247 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1248 // yet been processed by some connections, the dispatcher will wait for these motion
1249 // events to be processed before dispatching the key event. This is because these motion events
1250 // may cause a new window to be launched, which the user might expect to receive focus.
1251 // To prevent waiting forever for such events, just send the key to the currently focused window
1252 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1253 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1254 "just send the pending key event to the focused window.");
1255 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001256 }
1257 return false;
1258}
1259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001261 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001263 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 traceInboundQueueLengthLocked();
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001267 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001268 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1269 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001272 if (mTracer) {
1273 ensureEventTraced(keyEntry);
1274 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001275
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001276 // If a new up event comes in, and the pending event with same key code has been asked
1277 // to try again later because of the policy. We have to reset the intercept key wake up
1278 // time for it may have been handled in the policy and could be dropped.
1279 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1280 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001281 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001282 if (pendingKey.keyCode == keyEntry.keyCode &&
1283 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001284 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1285 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001286 pendingKey.interceptKeyWakeupTime = 0;
1287 needWake = true;
1288 }
1289 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 break;
1291 }
1292
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001293 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001294 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1295 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001296 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1297 if (mTracer) {
1298 ensureEventTraced(motionEntry);
1299 }
1300 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001306 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001307 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1308 break;
1309 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001310 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001311 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001312 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001313 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001314 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1315 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001316 // nothing to do
1317 break;
1318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320
1321 return needWake;
1322}
1323
Prabir Pradhan24047542023-11-02 17:14:59 +00001324void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001325 // Do not store sensor event in recent queue to avoid flooding the queue.
1326 if (entry->type != EventEntry::Type::SENSOR) {
1327 mRecentQueue.push_back(entry);
1328 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001329 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001330 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
1332}
1333
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001334sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1335 bool isStylus,
1336 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001338 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001339 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001340 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001341 continue;
1342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001344 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001345 if (!info.isSpy() &&
1346 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001347 return windowHandle;
1348 }
1349 }
1350 return nullptr;
1351}
1352
1353std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001354 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001355 if (touchedWindow == nullptr) {
1356 return {};
1357 }
1358 // Traverse windows from front to back until we encounter the touched window.
1359 std::vector<InputTarget> outsideTargets;
1360 const auto& windowHandles = getWindowHandlesLocked(displayId);
1361 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1362 if (windowHandle == touchedWindow) {
1363 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1364 // below the touched window will not get ACTION_OUTSIDE event.
1365 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001366 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001367
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001369 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001370 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1371 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001372 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1373 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001374 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 }
1376 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001377 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378}
1379
Prabir Pradhand65552b2021-10-07 11:23:50 -07001380std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001381 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001382 // Traverse windows from front to back and gather the touched spy windows.
1383 std::vector<sp<WindowInfoHandle>> spyWindows;
1384 const auto& windowHandles = getWindowHandlesLocked(displayId);
1385 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1386 const WindowInfo& info = *windowHandle->getInfo();
1387
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001388 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001389 continue;
1390 }
1391 if (!info.isSpy()) {
1392 // The first touched non-spy window was found, so return the spy windows touched so far.
1393 return spyWindows;
1394 }
1395 spyWindows.push_back(windowHandle);
1396 }
1397 return spyWindows;
1398}
1399
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 const char* reason;
1402 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001403 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001404 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001405 ALOGD("Dropped event because policy consumed it.");
1406 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001407 reason = "inbound event was dropped because the policy consumed it";
1408 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001409 case DropReason::DISABLED:
1410 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 ALOGI("Dropped event because input dispatch is disabled.");
1412 }
1413 reason = "inbound event was dropped because input dispatch is disabled";
1414 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001415 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001416 LOG(INFO) << "Dropping because the current application is not responding and the user "
1417 "has started interacting with a different application: "
1418 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 reason = "inbound event was dropped because the current application is not responding "
1420 "and the user has started interacting with a different application";
1421 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001422 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 ALOGI("Dropped event because it is stale.");
1424 reason = "inbound event was dropped because it is stale";
1425 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001426 case DropReason::NO_POINTER_CAPTURE:
1427 ALOGI("Dropped event because there is no window with Pointer Capture.");
1428 reason = "inbound event was dropped because there is no window with Pointer Capture";
1429 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001430 case DropReason::NOT_DROPPED: {
1431 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001436 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001437 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001438 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001439 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1440 options.displayId = keyEntry.displayId;
1441 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001445 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1447 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001448 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001449 options.displayId = motionEntry.displayId;
1450 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 synthesizeCancelationEventsForAllConnectionsLocked(options);
1452 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001453 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1454 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001455 options.displayId = motionEntry.displayId;
1456 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 synthesizeCancelationEventsForAllConnectionsLocked(options);
1458 }
1459 break;
1460 }
Chris Yef59a2f42020-10-16 12:55:26 -07001461 case EventEntry::Type::SENSOR: {
1462 break;
1463 }
arthurhungb89ccb02020-12-30 16:19:01 +08001464 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1465 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 break;
1467 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001468 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001469 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001470 case EventEntry::Type::CONFIGURATION_CHANGED:
1471 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001472 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001473 break;
1474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 }
1476}
1477
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001479 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480}
1481
Prabir Pradhancef936d2021-07-21 16:17:52 +00001482bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001483 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 return false;
1485 }
1486
1487 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001488 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001489 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001490 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1491 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return true;
1494}
1495
Prabir Pradhancef936d2021-07-21 16:17:52 +00001496void InputDispatcher::postCommandLocked(Command&& command) {
1497 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498}
1499
1500void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001501 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001502 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001503 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 releaseInboundEventLocked(entry);
1505 }
1506 traceInboundQueueLengthLocked();
1507}
1508
1509void InputDispatcher::releasePendingEventLocked() {
1510 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 }
1514}
1515
Prabir Pradhan24047542023-11-02 17:14:59 +00001516void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001517 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001519 if (DEBUG_DISPATCH_CYCLE) {
1520 ALOGD("Injected inbound event was dropped.");
1521 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 }
1524 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001525 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528}
1529
1530void InputDispatcher::resetKeyRepeatLocked() {
1531 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001532 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534}
1535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001537 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
Michael Wright2e732952014-09-24 13:26:59 -07001539 uint32_t policyFlags = entry->policyFlags &
1540 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001543 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1544 currentTime, entry->deviceId, entry->source,
1545 entry->displayId, policyFlags, entry->action, entry->flags,
1546 entry->keyCode, entry->scanCode, entry->metaState,
1547 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001550 if (mTracer) {
1551 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1552 }
1553
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557}
1558
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001561 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1562 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564
1565 // Reset key repeating in case a keyboard device was added or removed or something.
1566 resetKeyRepeatLocked();
1567
1568 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001569 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1570 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001571 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001572 };
1573 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 return true;
1575}
1576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1578 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001579 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1580 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1581 entry.deviceId);
1582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583
liushenxiang42232912021-05-21 20:24:09 +08001584 // Reset key repeating in case a keyboard device was disabled or enabled.
1585 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1586 resetKeyRepeatLocked();
1587 }
1588
Michael Wrightfb04fd52022-11-24 22:31:11 +00001589 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001590 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001592
1593 // Remove all active pointers from this device
1594 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1595 touchState.removeAllPointersForDevice(entry.deviceId);
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 return true;
1598}
1599
Vishnu Nairad321cd2020-08-20 16:40:21 -07001600void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001601 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001602 if (mPendingEvent != nullptr) {
1603 // Move the pending event to the front of the queue. This will give the chance
1604 // for the pending event to get dispatched to the newly focused window
1605 mInboundQueue.push_front(mPendingEvent);
1606 mPendingEvent = nullptr;
1607 }
1608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001609 std::unique_ptr<FocusEntry> focusEntry =
1610 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1611 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001612
1613 // This event should go to the front of the queue, but behind all other focus events
1614 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001615 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1616 [](const std::shared_ptr<const EventEntry>& event) {
1617 return event->type == EventEntry::Type::FOCUS;
1618 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001619
1620 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001622}
1623
Prabir Pradhan24047542023-11-02 17:14:59 +00001624void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1625 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001626 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001627 if (channel == nullptr) {
1628 return; // Window has gone away
1629 }
1630 InputTarget target;
1631 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001632 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001633 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1634 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001635 std::string reason = std::string("reason=").append(entry->reason);
1636 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001637 dispatchEventLocked(currentTime, entry, {target});
1638}
1639
Prabir Pradhan99987712020-11-10 18:43:05 -08001640void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001641 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001642 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001643 dropReason = DropReason::NOT_DROPPED;
1644
Prabir Pradhan99987712020-11-10 18:43:05 -08001645 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001647
1648 if (entry->pointerCaptureRequest.enable) {
1649 // Enable Pointer Capture.
1650 if (haveWindowWithPointerCapture &&
1651 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001652 // This can happen if pointer capture is disabled and re-enabled before we notify the
1653 // app of the state change, so there is no need to notify the app.
1654 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1655 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001656 }
1657 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001658 // This can happen if a window requests capture and immediately releases capture.
1659 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001660 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001661 return;
1662 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001663 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1664 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1665 return;
1666 }
1667
Vishnu Nairc519ff72021-01-21 08:23:08 -08001668 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001669 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1670 mWindowTokenWithPointerCapture = token;
1671 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001672 // Disable Pointer Capture.
1673 // We do not check if the sequence number matches for requests to disable Pointer Capture
1674 // for two reasons:
1675 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1676 // to disable capture with the same sequence number: one generated by
1677 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1678 // Capture being disabled in InputReader.
1679 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1680 // actual Pointer Capture state that affects events being generated by input devices is
1681 // in InputReader.
1682 if (!haveWindowWithPointerCapture) {
1683 // Pointer capture was already forcefully disabled because of focus change.
1684 dropReason = DropReason::NOT_DROPPED;
1685 return;
1686 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001687 token = mWindowTokenWithPointerCapture;
1688 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001689 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001690 setPointerCaptureLocked(false);
1691 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001692 }
1693
1694 auto channel = getInputChannelLocked(token);
1695 if (channel == nullptr) {
1696 // Window has gone away, clean up Pointer Capture state.
1697 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001698 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001699 setPointerCaptureLocked(false);
1700 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001701 return;
1702 }
1703 InputTarget target;
1704 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001705 entry->dispatchInProgress = true;
1706 dispatchEventLocked(currentTime, entry, {target});
1707
1708 dropReason = DropReason::NOT_DROPPED;
1709}
1710
Prabir Pradhan24047542023-11-02 17:14:59 +00001711void InputDispatcher::dispatchTouchModeChangeLocked(
1712 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001713 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001714 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001715 if (windowHandles.empty()) {
1716 return;
1717 }
1718 const std::vector<InputTarget> inputTargets =
1719 getInputTargetsFromWindowHandlesLocked(windowHandles);
1720 if (inputTargets.empty()) {
1721 return;
1722 }
1723 entry->dispatchInProgress = true;
1724 dispatchEventLocked(currentTime, entry, inputTargets);
1725}
1726
1727std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1728 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1729 std::vector<InputTarget> inputTargets;
1730 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001731 const sp<IBinder>& token = handle->getToken();
1732 if (token == nullptr) {
1733 continue;
1734 }
1735 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1736 if (channel == nullptr) {
1737 continue; // Window has gone away
1738 }
1739 InputTarget target;
1740 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001741 inputTargets.push_back(target);
1742 }
1743 return inputTargets;
1744}
1745
Prabir Pradhan24047542023-11-02 17:14:59 +00001746bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001747 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 if (!entry->dispatchInProgress) {
1750 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1751 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1752 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1753 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001754 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 // We have seen two identical key downs in a row which indicates that the device
1756 // driver is automatically generating key repeats itself. We take note of the
1757 // repeat here, but we disable our own next key repeat timer since it is clear that
1758 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001759 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1760 // Make sure we don't get key down from a different device. If a different
1761 // device Id has same key pressed down, the new device Id will replace the
1762 // current one to hold the key repeat with repeat count reset.
1763 // In the future when got a KEY_UP on the device id, drop it and do not
1764 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1766 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001767 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 } else {
1769 // Not a repeat. Save key down state in case we do see a repeat later.
1770 resetKeyRepeatLocked();
1771 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1772 }
1773 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001774 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1775 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001776 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001777 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001778 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1779 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 resetKeyRepeatLocked();
1782 }
1783
1784 if (entry->repeatCount == 1) {
1785 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1786 } else {
1787 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1788 }
1789
1790 entry->dispatchInProgress = true;
1791
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001792 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794
1795 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001796 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001798 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return false; // wait until next wakeup
1800 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001801 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 entry->interceptKeyWakeupTime = 0;
1803 }
1804
1805 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001806 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001808 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001809 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001810
1811 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1812 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1813 };
1814 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001815 // Poke user activity for keys not passed to user
1816 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 return false; // wait for the command to run
1818 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001819 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001821 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001822 if (*dropReason == DropReason::NOT_DROPPED) {
1823 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825 }
1826
1827 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001828 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001829 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1831 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001832 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001833 // Poke user activity for undispatched keys
1834 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 return true;
1836 }
1837
1838 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001839 InputEventInjectionResult injectionResult;
1840 sp<WindowInfoHandle> focusedWindow =
1841 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1842 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 return false;
1845 }
1846
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001847 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 return true;
1850 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001851 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1852
1853 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001854 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1855 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001857 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001860 if (mTracer) {
1861 ensureEventTraced(*entry);
1862 for (const auto& target : inputTargets) {
1863 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1864 }
1865 }
1866
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 // Dispatch the key.
1868 dispatchEventLocked(currentTime, entry, inputTargets);
1869 return true;
1870}
1871
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001872void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001873 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1874 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1875 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1876 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1877 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1878 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1879 entry.metaState, entry.repeatCount, entry.downTime);
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881}
1882
Prabir Pradhancef936d2021-07-21 16:17:52 +00001883void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001884 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001885 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001886 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1887 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1888 "source=0x%x, sensorType=%s",
1889 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001890 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001891 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001892 auto command = [this, entry]() REQUIRES(mLock) {
1893 scoped_unlock unlock(mLock);
1894
1895 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001896 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001897 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001898 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1899 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001900 };
1901 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001902}
1903
1904bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001905 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1906 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001907 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001908 }
Chris Yef59a2f42020-10-16 12:55:26 -07001909 { // acquire lock
1910 std::scoped_lock _l(mLock);
1911
1912 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001913 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001914 if (entry->type == EventEntry::Type::SENSOR) {
1915 it = mInboundQueue.erase(it);
1916 releaseInboundEventLocked(entry);
1917 }
1918 }
1919 }
1920 return true;
1921}
1922
Prabir Pradhan24047542023-11-02 17:14:59 +00001923bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1924 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001925 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001926 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 entry->dispatchInProgress = true;
1930
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
1933
1934 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001935 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001936 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1938 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 return true;
1940 }
1941
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001942 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943
1944 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001945 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 if (isPointerEvent) {
1949 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001950
1951 if (mDragState &&
1952 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1953 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1954 pilferPointersLocked(mDragState->dragWindow->getToken());
1955 }
1956
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001957 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001958 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001959 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1960 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 } else {
1962 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001963 sp<WindowInfoHandle> focusedWindow =
1964 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1965 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1966 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001967 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1968 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1969 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 return false;
1974 }
1975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001976 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001977 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 return true;
1979 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001981 CancelationOptions::Mode mode(
1982 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1983 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 CancelationOptions options(mode, "input event injection failed");
1985 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) {
arthurhungb89ccb02020-12-30 16:19:01 +08002017 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
2018 if (channel == nullptr) {
2019 return; // Window has gone away
2020 }
2021 InputTarget target;
2022 target.inputChannel = channel;
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 Vishniakou1069fa82023-04-19 12:14:39 -07002075 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002076 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002077 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002078 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002080 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2081 LOG(INFO) << "Dropping event delivery to target with channel "
2082 << inputTarget.inputChannel->getName()
2083 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
2086 }
2087}
2088
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002089void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2091 // If the policy decides to close the app, we will get a channel removal event via
2092 // unregisterInputChannel, and will clean up the connection that way. We are already not
2093 // sending new pointers to the connection when it blocked, but focused events will continue to
2094 // pile up.
2095 ALOGW("Canceling events for %s because it is unresponsive",
2096 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002097 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002098 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099 "application not responding");
2100 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102}
2103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002105 if (DEBUG_FOCUS) {
2106 ALOGD("Resetting ANR timeouts.");
2107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108
2109 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002111 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112}
2113
Tiger Huang721e26f2018-07-24 22:26:19 +08002114/**
2115 * Get the display id that the given event should go to. If this event specifies a valid display id,
2116 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2117 * Focused display is the display that the user most recently interacted with.
2118 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002120 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002121 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002122 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2124 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002125 break;
2126 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002127 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002128 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2129 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002130 break;
2131 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002132 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002133 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002134 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002135 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002136 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002137 case EventEntry::Type::SENSOR:
2138 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002139 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 return ADISPLAY_ID_NONE;
2141 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002142 }
2143 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2144}
2145
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2147 const char* focusedWindowName) {
2148 if (mAnrTracker.empty()) {
2149 // already processed all events that we waited for
2150 mKeyIsWaitingForEventsTimeout = std::nullopt;
2151 return false;
2152 }
2153
2154 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2155 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002156 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002157 mKeyIsWaitingForEventsTimeout = currentTime +
2158 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2159 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002160 return true;
2161 }
2162
2163 // We still have pending events, and already started the timer
2164 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2165 return true; // Still waiting
2166 }
2167
2168 // Waited too long, and some connection still hasn't processed all motions
2169 // Just send the key to the focused window
2170 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2171 focusedWindowName);
2172 mKeyIsWaitingForEventsTimeout = std::nullopt;
2173 return false;
2174}
2175
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002176sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002177 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002178 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180
Tiger Huang721e26f2018-07-24 22:26:19 +08002181 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002182 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002183 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002184 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2185
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 // If there is no currently focused window and no focused application
2187 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002188 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2189 ALOGI("Dropping %s event because there is no focused window or focused application in "
2190 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002191 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002192 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194
Vishnu Nair062a8672021-09-03 16:07:44 -07002195 // Drop key events if requested by input feature
2196 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002197 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002198 }
2199
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002200 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2201 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2202 // start interacting with another application via touch (app switch). This code can be removed
2203 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2204 // an app is expected to have a focused window.
2205 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2206 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2207 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002208 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2209 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2210 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002211 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002212 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002213 ALOGW("Waiting because no window has focus but %s may eventually add a "
2214 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002215 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002216 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217 outInjectionResult = InputEventInjectionResult::PENDING;
2218 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002219 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2220 // Already raised ANR. Drop the event
2221 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002222 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002223 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002224 } else {
2225 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002226 outInjectionResult = InputEventInjectionResult::PENDING;
2227 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002228 }
2229 }
2230
2231 // we have a valid, non-null focused window
2232 resetNoFocusedWindowTimeoutLocked();
2233
Prabir Pradhan5735a322022-04-11 17:23:34 +00002234 // Verify targeted injection.
2235 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2236 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002237 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2238 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 }
2240
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002241 if (focusedWindowHandle->getInfo()->inputConfig.test(
2242 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002244 outInjectionResult = InputEventInjectionResult::PENDING;
2245 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 }
2247
2248 // If the event is a key event, then we must wait for all previous events to
2249 // complete before delivering it because previous events may have the
2250 // side-effect of transferring focus to a different window and we want to
2251 // ensure that the following keys are sent to the new window.
2252 //
2253 // Suppose the user touches a button in a window then immediately presses "A".
2254 // If the button causes a pop-up window to appear then we want to ensure that
2255 // the "A" key is delivered to the new pop-up window. This is because users
2256 // often anticipate pending UI changes when typing on a keyboard.
2257 // To obtain this behavior, we must serialize key events with respect to all
2258 // prior input events.
2259 if (entry.type == EventEntry::Type::KEY) {
2260 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002261 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::PENDING;
2263 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002267 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2268 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269}
2270
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002271/**
2272 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2273 * that are currently unresponsive.
2274 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002275std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2276 const std::vector<Monitor>& monitors) const {
2277 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002278 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002279 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002280 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002281 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002282 if (connection == nullptr) {
2283 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002284 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002285 return false;
2286 }
2287 if (!connection->responsive) {
2288 ALOGW("Unresponsive monitor %s will not get the new gesture",
2289 connection->inputChannel->getName().c_str());
2290 return false;
2291 }
2292 return true;
2293 });
2294 return responsiveMonitors;
2295}
2296
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002297std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002298 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002299 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002300 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002302 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 // For security reasons, we defer updating the touch state until we are sure that
2304 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002305 const int32_t displayId = entry.displayId;
2306 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002307 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308
2309 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002310 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002312 // Copy current touch state into tempTouchState.
2313 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2314 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002315 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002316 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2318 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002319 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002320 }
2321
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002322 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002323
2324 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2325 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002327 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2328 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002329 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002330 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2331 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002332 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2333 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2334 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002335 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002336
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002337 if (newGesture) {
2338 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002339 }
2340
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002341 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2342 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2343 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 }
2345
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002346 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002347 if (wasDown) {
2348 // Started hovering, but the device is already down: reject the hover event
2349 LOG(ERROR) << "Got hover event " << entry.getDescription()
2350 << " but the device is already down " << oldState->dump();
2351 outInjectionResult = InputEventInjectionResult::FAILED;
2352 return {};
2353 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002354 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2355 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002356 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002357 }
2358
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2360 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002361 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002362 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002363 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002364 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2365 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002366 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002367 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002368 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002369
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002370 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002371 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002374 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002375 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002377 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002378 }
2379
Prabir Pradhan5735a322022-04-11 17:23:34 +00002380 // Verify targeted injection.
2381 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2382 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002383 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002384 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002385 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002386 }
2387
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002388 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002389 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2391 // New window supports splitting, but we should never split mouse events.
2392 isSplit = !isFromMouse;
2393 } else if (isSplit) {
2394 // New window does not support splitting but we have already split events.
2395 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002396 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2397 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002398 newTouchedWindowHandle = nullptr;
2399 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 } else {
2401 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002402 // be delivered to a new window which supports split touch. Pointers from a mouse device
2403 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002404 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002405 }
2406
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002407 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002408 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002409 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002410 // Process the foreground window first so that it is the first to receive the event.
2411 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412 }
2413
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002414 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002415 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2416 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002417 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002418 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002419 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002420 }
2421
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002422 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002423 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 continue;
2425 }
2426
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002427 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002428 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002429 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002430 }
2431
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002432 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002433 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002434
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002435 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2436 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002437 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002438 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002439
2440 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002441 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002442 }
2443 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002444 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002445 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002446 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002447 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002448
2449 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002450
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002451 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002452 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2453 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002454 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002455 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002456 isDownOrPointerDown
2457 ? std::make_optional(entry.eventTime)
2458 : std::nullopt);
2459 // If this is the pointer going down and the touched window has a wallpaper
2460 // then also add the touched wallpaper windows so they are locked in for the
2461 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2462 // SCROLL because the wallpaper engine only supports touch events. We would need to
2463 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2464 // handle these events.
2465 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002466 windowHandle->getInfo()->inputConfig.test(
2467 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2468 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2469 if (wallpaper != nullptr) {
2470 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2471 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002472 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002473 if (isSplit) {
2474 wallpaperFlags |= InputTarget::Flags::SPLIT;
2475 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002476 tempTouchState.addOrUpdateWindow(wallpaper,
2477 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002478 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002479 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002480 }
2481 }
2482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002484
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002485 // If a window is already pilfering some pointers, give it this new pointer as well and
2486 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2487 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002488 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002489 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002490 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002491 // This window is already pilfering some pointers, and this new pointer is also
2492 // going to it. Therefore, take over this pointer and don't give it to anyone
2493 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002494 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002495 }
2496 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002497
2498 // Restrict all pilfered pointers to the pilfering windows.
2499 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 } else {
2501 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2502
2503 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002504 if (!tempTouchState.isDown(entry.deviceId) &&
2505 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002506 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2507 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2508 << " is not down or we previously dropped the pointer down event in "
2509 << "display " << displayId << ": " << entry.getDescription();
2510 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002511 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002512 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
2514
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002515 // If the pointer is not currently hovering, then ignore the event.
2516 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2517 const int32_t pointerId = entry.pointerProperties[0].id;
2518 if (oldState == nullptr ||
2519 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2520 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2521 "display "
2522 << displayId << ": " << entry.getDescription();
2523 outInjectionResult = InputEventInjectionResult::FAILED;
2524 return {};
2525 }
2526 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2527 }
2528
arthurhung6d4bed92021-03-17 11:59:33 +08002529 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002530
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002532 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002533 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002534 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002535 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002536 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002537 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002538 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002539 sp<WindowInfoHandle> newTouchedWindowHandle =
2540 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002541
Prabir Pradhan5735a322022-04-11 17:23:34 +00002542 // Verify targeted injection.
2543 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2544 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002545 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002546 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002547 }
2548
Vishnu Nair062a8672021-09-03 16:07:44 -07002549 // Drop touch events if requested by input feature
2550 if (newTouchedWindowHandle != nullptr &&
2551 shouldDropInput(entry, newTouchedWindowHandle)) {
2552 newTouchedWindowHandle = nullptr;
2553 }
2554
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002555 if (newTouchedWindowHandle != nullptr &&
2556 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002557 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002558 oldTouchedWindowHandle->getName().c_str(),
2559 newTouchedWindowHandle->getName().c_str(), displayId);
2560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002562 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002563 const PointerProperties& pointer = entry.pointerProperties[0];
2564 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002565
2566 const TouchedWindow& touchedWindow =
2567 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002568 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002569 InputTarget::DispatchMode::SLIPPERY_EXIT,
2570 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002571 touchedWindow.getDownTimeInTarget(entry.deviceId),
2572 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573
2574 // Make a slippery entrance into the new window.
2575 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002576 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
2578
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002579 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002580 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002581 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002584 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
2586 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002587 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002588 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002589 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590 }
2591
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002592 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2593 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002594 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002595 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002596
2597 // Check if the wallpaper window should deliver the corresponding event.
2598 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002599 tempTouchState, entry.deviceId, pointer, targets);
2600 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002601 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603 }
Arthur Hung96483742022-11-15 03:30:48 +00002604
2605 // Update the pointerIds for non-splittable when it received pointer down.
2606 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2607 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002608 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002609 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2610 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002611 // Ignore drag window for it should just track one pointer.
2612 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2613 continue;
2614 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002615 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002616 }
2617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 }
2619
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002620 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002621 {
2622 std::vector<TouchedWindow> hoveringWindows =
2623 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2624 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002625 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002626 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2627 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002628 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002629 if (!target) {
2630 continue;
2631 }
2632 // Hardcode to single hovering pointer for now.
2633 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2634 pointerIds.set(entry.pointerProperties[0].id);
2635 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2636 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639
Prabir Pradhan5735a322022-04-11 17:23:34 +00002640 // Ensure that all touched windows are valid for injection.
2641 if (entry.injectionState != nullptr) {
2642 std::string errs;
2643 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002644 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2645 if (err) errs += "\n - " + *err;
2646 }
2647 if (!errs.empty()) {
2648 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002649 "%s:%s",
2650 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002651 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002652 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002653 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002654 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002655
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002656 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2657 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002659 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002660 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002661 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002662 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002663 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002664 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002665 sp<WindowInfoHandle> targetWindow =
2666 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2667 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2668 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
2671 }
2672 }
2673 }
2674
Harry Cuttsb166c002023-05-09 13:06:05 +00002675 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2676 // only want the system UI to handle these gestures.
2677 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2678 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2679 if (isTouchpadNavGesture) {
2680 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2681 }
2682
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002683 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002684 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002685 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002686 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002687 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002688 continue;
2689 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002690 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002691 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002692 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002693 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002694
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002695 // During targeted injection, only allow owned targets to receive events
2696 std::erase_if(targets, [&](const InputTarget& target) {
2697 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2698 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2699 if (err) {
2700 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2701 << ": " << (*err);
2702 return true;
2703 }
2704 return false;
2705 });
2706
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002707 if (targets.empty()) {
2708 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2709 outInjectionResult = InputEventInjectionResult::FAILED;
2710 return {};
2711 }
2712
2713 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2714 // window that is actually receiving the entire gesture.
2715 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002716 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002717 })) {
2718 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2719 << entry.getDescription();
2720 outInjectionResult = InputEventInjectionResult::FAILED;
2721 return {};
2722 }
2723
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002724 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725
Prabir Pradhan502a7252023-12-01 16:11:24 +00002726 // Now that we have generated all of the input targets for this event, reset the dispatch
2727 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002728 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002729 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002730 }
2731
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002732 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002733 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002734 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002735 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002736 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002738 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002739 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2740 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002741 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2742 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2743 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002746 // Save changes unless the action was scroll in which case the temporary touch
2747 // state was only valid for this one action.
2748 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002749 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002750 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002751 mTouchStatesByDisplay[displayId] = tempTouchState;
2752 } else {
2753 mTouchStatesByDisplay.erase(displayId);
2754 }
2755 }
2756
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002757 if (tempTouchState.windows.empty()) {
2758 mTouchStatesByDisplay.erase(displayId);
2759 }
2760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002761 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762}
2763
arthurhung6d4bed92021-03-17 11:59:33 +08002764void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002765 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2766 // have an explicit reason to support it.
2767 constexpr bool isStylus = false;
2768
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002769 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002770 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002771 if (dropWindow) {
2772 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002773 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002774 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002775 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002776 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002777 }
2778 mDragState.reset();
2779}
2780
2781void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002782 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002783 return;
2784 }
2785
arthurhung6d4bed92021-03-17 11:59:33 +08002786 if (!mDragState->isStartDrag) {
2787 mDragState->isStartDrag = true;
2788 mDragState->isStylusButtonDownAtStart =
2789 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2790 }
2791
Arthur Hung54745652022-04-20 07:17:41 +00002792 // Find the pointer index by id.
2793 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002794 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002795 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2796 if (pointerProperties.id == mDragState->pointerId) {
2797 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002798 }
Arthur Hung54745652022-04-20 07:17:41 +00002799 }
arthurhung6d4bed92021-03-17 11:59:33 +08002800
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002801 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002802 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002803 }
2804
2805 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2806 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2807 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2808
2809 switch (maskedAction) {
2810 case AMOTION_EVENT_ACTION_MOVE: {
2811 // Handle the special case : stylus button no longer pressed.
2812 bool isStylusButtonDown =
2813 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2814 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2815 finishDragAndDrop(entry.displayId, x, y);
2816 return;
2817 }
2818
2819 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2820 // until we have an explicit reason to support it.
2821 constexpr bool isStylus = false;
2822
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002823 sp<WindowInfoHandle> hoverWindowHandle =
2824 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2825 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002826 // enqueue drag exit if needed.
2827 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2828 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2829 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002830 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002831 y);
2832 }
2833 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2834 }
2835 // enqueue drag location if needed.
2836 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002837 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002838 }
2839 break;
2840 }
2841
2842 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002843 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002844 break;
2845 }
2846 // The drag pointer is up.
2847 [[fallthrough]];
2848 case AMOTION_EVENT_ACTION_UP:
2849 finishDragAndDrop(entry.displayId, x, y);
2850 break;
2851 case AMOTION_EVENT_ACTION_CANCEL: {
2852 ALOGD("Receiving cancel when drag and drop.");
2853 sendDropWindowCommandLocked(nullptr, 0, 0);
2854 mDragState.reset();
2855 break;
2856 }
arthurhungb89ccb02020-12-30 16:19:01 +08002857 }
2858}
2859
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002860std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2861 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002862 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002863 std::optional<nsecs_t> firstDownTimeInTarget) const {
2864 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2865 if (inputChannel == nullptr) {
2866 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2867 return {};
2868 }
2869 InputTarget inputTarget;
2870 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002871 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002872 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002873 inputTarget.flags = targetFlags;
2874 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2875 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2876 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2877 if (displayInfoIt != mDisplayInfos.end()) {
2878 inputTarget.displayTransform = displayInfoIt->second.transform;
2879 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002880 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002881 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2882 }
2883 return inputTarget;
2884}
2885
chaviw98318de2021-05-19 16:45:23 -05002886void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002887 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002888 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002889 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002890 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002891 std::vector<InputTarget>::iterator it =
2892 std::find_if(inputTargets.begin(), inputTargets.end(),
2893 [&windowHandle](const InputTarget& inputTarget) {
2894 return inputTarget.inputChannel->getConnectionToken() ==
2895 windowHandle->getToken();
2896 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002897
chaviw98318de2021-05-19 16:45:23 -05002898 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002899
2900 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002901 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002902 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2903 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002904 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002905 return;
2906 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002907 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002908 it = inputTargets.end() - 1;
2909 }
2910
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002911 if (it->flags != targetFlags) {
2912 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2913 }
2914 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2915 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2916 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2917 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002918}
2919
2920void InputDispatcher::addPointerWindowTargetLocked(
2921 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002922 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2923 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2924 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002925 if (pointerIds.none()) {
2926 for (const auto& target : inputTargets) {
2927 LOG(INFO) << "Target: " << target;
2928 }
2929 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2930 return;
2931 }
2932 std::vector<InputTarget>::iterator it =
2933 std::find_if(inputTargets.begin(), inputTargets.end(),
2934 [&windowHandle](const InputTarget& inputTarget) {
2935 return inputTarget.inputChannel->getConnectionToken() ==
2936 windowHandle->getToken();
2937 });
2938
2939 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2940 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2941 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2942 // input targets for hovering pointers and for touching pointers.
2943 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2944 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002945 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002946 // Force the code below to create a new input target
2947 it = inputTargets.end();
2948 }
2949
2950 const WindowInfo* windowInfo = windowHandle->getInfo();
2951
2952 if (it == inputTargets.end()) {
2953 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002954 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2955 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002956 if (!target) {
2957 return;
2958 }
2959 inputTargets.push_back(*target);
2960 it = inputTargets.end() - 1;
2961 }
2962
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002963 if (it->dispatchMode != dispatchMode) {
2964 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2965 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2966 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002967 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002968 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2969 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002970 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002971 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002972 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002973 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2974 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002975
chaviw1ff3d1e2020-07-01 15:53:47 -07002976 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977}
2978
Michael Wright3dd60e22019-03-27 22:06:44 +00002979void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002980 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002981 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2982 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002983
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002984 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2985 InputTarget target;
2986 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002987 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2988 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002989 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2990 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002991 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002992 target.setDefaultPointerTransform(target.displayTransform);
2993 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995}
2996
Robert Carrc9bf1d32020-04-13 17:21:08 -07002997/**
2998 * Indicate whether one window handle should be considered as obscuring
2999 * another window handle. We only check a few preconditions. Actually
3000 * checking the bounds is left to the caller.
3001 */
chaviw98318de2021-05-19 16:45:23 -05003002static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
3003 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003004 // Compare by token so cloned layers aren't counted
3005 if (haveSameToken(windowHandle, otherHandle)) {
3006 return false;
3007 }
3008 auto info = windowHandle->getInfo();
3009 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003010 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003011 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003012 } else if (otherInfo->alpha == 0 &&
3013 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003014 // Those act as if they were invisible, so we don't need to flag them.
3015 // We do want to potentially flag touchable windows even if they have 0
3016 // opacity, since they can consume touches and alter the effects of the
3017 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003019 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3020 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003021 } else if (info->ownerUid == otherInfo->ownerUid) {
3022 // If ownerUid is the same we don't generate occlusion events as there
3023 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003024 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003025 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003026 return false;
3027 } else if (otherInfo->displayId != info->displayId) {
3028 return false;
3029 }
3030 return true;
3031}
3032
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003033/**
3034 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3035 * untrusted, one should check:
3036 *
3037 * 1. If result.hasBlockingOcclusion is true.
3038 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3039 * BLOCK_UNTRUSTED.
3040 *
3041 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3042 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3043 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3044 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3045 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3046 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3047 *
3048 * If neither of those is true, then it means the touch can be allowed.
3049 */
3050InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003051 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3052 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003053 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003054 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003055 TouchOcclusionInfo info;
3056 info.hasBlockingOcclusion = false;
3057 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003058 info.obscuringUid = gui::Uid::INVALID;
3059 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003060 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003061 if (windowHandle == otherHandle) {
3062 break; // All future windows are below us. Exit early.
3063 }
chaviw98318de2021-05-19 16:45:23 -05003064 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003065 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3066 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003067 if (DEBUG_TOUCH_OCCLUSION) {
3068 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003069 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003070 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003071 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3072 // we perform the checks below to see if the touch can be propagated or not based on the
3073 // window's touch occlusion mode
3074 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3075 info.hasBlockingOcclusion = true;
3076 info.obscuringUid = otherInfo->ownerUid;
3077 info.obscuringPackage = otherInfo->packageName;
3078 break;
3079 }
3080 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003081 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003082 float opacity =
3083 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3084 // Given windows A and B:
3085 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3086 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3087 opacityByUid[uid] = opacity;
3088 if (opacity > info.obscuringOpacity) {
3089 info.obscuringOpacity = opacity;
3090 info.obscuringUid = uid;
3091 info.obscuringPackage = otherInfo->packageName;
3092 }
3093 }
3094 }
3095 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003096 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003097 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003098 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003099 return info;
3100}
3101
chaviw98318de2021-05-19 16:45:23 -05003102std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003103 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003104 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003105 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3106 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3107 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003108 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003109 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003110 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3111 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003112 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3113 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3114 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003115 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003116}
3117
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003118bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3119 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003120 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3121 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003122 return false;
3123 }
3124 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003125 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003126 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003127 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003128 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3129 return false;
3130 }
3131 return true;
3132}
3133
chaviw98318de2021-05-19 16:45:23 -05003134bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003137 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3138 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003139 if (windowHandle == otherHandle) {
3140 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
chaviw98318de2021-05-19 16:45:23 -05003142 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003143 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003144 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 return true;
3146 }
3147 }
3148 return false;
3149}
3150
chaviw98318de2021-05-19 16:45:23 -05003151bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003152 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003153 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3154 const WindowInfo* windowInfo = windowHandle->getInfo();
3155 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003156 if (windowHandle == otherHandle) {
3157 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003158 }
chaviw98318de2021-05-19 16:45:23 -05003159 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003160 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003161 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003162 return true;
3163 }
3164 }
3165 return false;
3166}
3167
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003168std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003169 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003170 if (applicationHandle != nullptr) {
3171 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003172 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 } else {
3174 return applicationHandle->getName();
3175 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003176 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003177 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003179 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181}
3182
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003183void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003184 if (!isUserActivityEvent(eventEntry)) {
3185 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003186 return;
3187 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003188
3189 const int32_t eventType = getUserActivityEventType(eventEntry);
3190 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3191 // Note that we're directly getting the time diff between the current event and the previous
3192 // event. This is assuming that the first user event always happens at a timestamp that is
3193 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3194 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3195 // value than the potential first user activity event time, so this is ok.
3196 std::chrono::nanoseconds timeSinceLastEvent =
3197 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3198 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3199 return;
3200 }
3201 }
3202
Tiger Huang721e26f2018-07-24 22:26:19 +08003203 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003204 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003205 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003206 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003207 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003208 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003209 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211 }
3212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003213 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003214 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003215 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3216 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 return;
3218 }
Josep del Riob3981622023-04-18 15:49:45 +00003219 if (windowDisablingUserActivityInfo != nullptr) {
3220 if (DEBUG_DISPATCH_CYCLE) {
3221 ALOGD("Not poking user activity: disabled by window '%s'.",
3222 windowDisablingUserActivityInfo->name.c_str());
3223 }
3224 return;
3225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003228 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003229 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3230 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 return;
3232 }
Josep del Riob3981622023-04-18 15:49:45 +00003233 // If the key code is unknown, we don't consider it user activity
3234 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3235 return;
3236 }
3237 // Don't inhibit events that were intercepted or are not passed to
3238 // the apps, like system shortcuts
3239 if (windowDisablingUserActivityInfo != nullptr &&
3240 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3241 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3242 if (DEBUG_DISPATCH_CYCLE) {
3243 ALOGD("Not poking user activity: disabled by window '%s'.",
3244 windowDisablingUserActivityInfo->name.c_str());
3245 }
3246 return;
3247 }
3248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003251 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003252 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003253 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003254 break;
3255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003258 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003259 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3260 REQUIRES(mLock) {
3261 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003262 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003263 };
3264 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265}
3266
3267void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003268 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003269 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003270 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003271 ATRACE_NAME_IF(ATRACE_ENABLED(),
3272 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3273 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003274 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003276 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003278 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003279 inputTarget.getPointerInfoString().c_str());
3280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
3282 // Skip this event if the connection status is not normal.
3283 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003284 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003285 if (DEBUG_DISPATCH_CYCLE) {
3286 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003287 connection->getInputChannelName().c_str(),
3288 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 return;
3291 }
3292
3293 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003294 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003295 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003297 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003299 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003300 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003301 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3302 logDispatchStateLocked();
3303 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3304 "target on connection "
3305 << connection->getInputChannelName() << " for "
3306 << originalMotionEntry.getDescription();
3307 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003309 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3310 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 if (!splitMotionEntry) {
3312 return; // split event was dropped
3313 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003314 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3315 std::string reason = std::string("reason=pointer cancel on split window");
3316 android_log_event_list(LOGTAG_INPUT_CANCEL)
3317 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3318 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003319 if (DEBUG_FOCUS) {
3320 ALOGD("channel '%s' ~ Split motion event.",
3321 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003322 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003323 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003324 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3325 std::move(splitMotionEntry),
3326 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 return;
3328 }
3329 }
3330
3331 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003332 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3333 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334}
3335
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003336void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3337 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3338 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003339 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003340 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3341 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003342 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003343
hongzuo liu95785e22022-09-06 02:51:35 +00003344 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003346 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
3348 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003349 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 startDispatchCycleLocked(currentTime, connection);
3351 }
3352}
3353
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003354void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003355 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003356 const InputTarget& inputTarget) {
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003357 // TODO(b/210460522): Verify all targets excluding global monitors are associated with a window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 // This is a new event.
3359 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003360 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003361 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags, mWindowInfosVsyncId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003363 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3364 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003365 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003367 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003368 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003369 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3370 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003371 LOG(WARNING) << "channel " << connection->getInputChannelName()
3372 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 return; // skip the inconsistent event
3374 }
3375 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003378 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003379 std::shared_ptr<const MotionEntry> resolvedMotion =
3380 std::static_pointer_cast<const MotionEntry>(eventEntry);
3381 {
3382 // Determine the resolved motion entry.
3383 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3384 int32_t resolvedAction = motionEntry.action;
3385 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003387 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003388 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003389 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003390 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003391 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003392 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003393 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003394 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003395 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003396 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3397 }
3398 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3399 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3400 motionEntry.displayId)) {
3401 if (DEBUG_DISPATCH_CYCLE) {
3402 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3403 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3404 "enter event";
3405 }
3406 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3407 }
3408
3409 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3410 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3411 }
3412 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3413 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3414 }
3415 if (dispatchEntry->targetFlags.test(
3416 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3417 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3418 }
3419
3420 dispatchEntry->resolvedFlags = resolvedFlags;
3421 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003422 std::optional<std::vector<PointerProperties>> usingProperties;
3423 std::optional<std::vector<PointerCoords>> usingCoords;
3424 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3425 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3426 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3427 // the dispatcher, and therefore the coordinates of this event are currently
3428 // incorrect. These events should use the coordinates of the last dispatched
3429 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3430 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3431 std::optional<std::pair<std::vector<PointerProperties>,
3432 std::vector<PointerCoords>>>
3433 pointerInfo =
3434 connection->inputState.getPointersOfLastEvent(motionEntry,
3435 hovering);
3436 if (pointerInfo) {
3437 usingProperties = pointerInfo->first;
3438 usingCoords = pointerInfo->second;
3439 }
3440 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003441 // Generate a new MotionEntry with a new eventId using the resolved action and
3442 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003443 resolvedMotion = std::make_shared<
3444 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3445 motionEntry.eventTime, motionEntry.deviceId,
3446 motionEntry.source, motionEntry.displayId,
3447 motionEntry.policyFlags, resolvedAction,
3448 motionEntry.actionButton, resolvedFlags,
3449 motionEntry.metaState, motionEntry.buttonState,
3450 motionEntry.classification, motionEntry.edgeFlags,
3451 motionEntry.xPrecision, motionEntry.yPrecision,
3452 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3453 motionEntry.downTime,
3454 usingProperties.value_or(motionEntry.pointerProperties),
3455 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003456 if (ATRACE_ENABLED()) {
3457 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3458 ") to MotionEvent(id=0x%" PRIx32 ").",
3459 motionEntry.id, resolvedMotion->id);
3460 ATRACE_NAME(message.c_str());
3461 }
3462
3463 // Set the resolved motion entry in the DispatchEntry.
3464 dispatchEntry->eventEntry = resolvedMotion;
3465 eventEntry = resolvedMotion;
3466 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003469 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3470 // devices being active at the same time in the same window, so if a new device is
3471 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003472 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003473 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003474 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003475 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003476 << connection->getInputChannelName() << " with event "
3477 << cancelEvent->getDescription();
3478 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3479 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhanadc59b42023-12-15 05:34:11 +00003480 ftl::Flags<InputTarget::Flags>(), mWindowInfosVsyncId);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003481
3482 // Send these cancel events to the queue before sending the event from the new
3483 // device.
3484 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3485 }
3486
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003487 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003489 LOG(WARNING) << "channel " << connection->getInputChannelName()
3490 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 return; // skip the inconsistent event
3492 }
3493
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003494 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3495 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003496 // Skip reporting pointer down outside focus to the policy.
3497 break;
3498 }
3499
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003500 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003501 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003502
3503 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003505 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003506 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003507 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3508 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003509 break;
3510 }
Chris Yef59a2f42020-10-16 12:55:26 -07003511 case EventEntry::Type::SENSOR: {
3512 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3513 break;
3514 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003515 case EventEntry::Type::CONFIGURATION_CHANGED:
3516 case EventEntry::Type::DEVICE_RESET: {
3517 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003518 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003519 break;
3520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
3522
3523 // Remember that we are waiting for this dispatch to complete.
3524 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003525 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
3527
3528 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003529 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003530 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003531}
3532
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003533/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003534 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003535 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003536 * The first role is to log input interaction with windows, which helps determine what the user was
3537 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3538 * that user started interacting with launcher window, as well as any other window that received
3539 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3540 * when the set of tokens that received the event changes. It is not logged again as long as the
3541 * user is interacting with the same windows.
3542 *
3543 * The second role is to track input device activity for metrics collection. For each input event,
3544 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3545 * input_interaction logs, the device interaction is reported even when the set of interaction
3546 * tokens do not change.
3547 *
3548 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3549 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003550 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003551void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3552 const std::vector<InputTarget>& targets) {
3553 int32_t deviceId;
3554 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003555 // Skip ACTION_UP events, and all events other than keys and motions
3556 if (entry.type == EventEntry::Type::KEY) {
3557 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3558 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3559 return;
3560 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003561 deviceId = keyEntry.deviceId;
3562 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003563 } else if (entry.type == EventEntry::Type::MOTION) {
3564 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3565 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003566 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3567 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003568 return;
3569 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003570 deviceId = motionEntry.deviceId;
3571 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003572 } else {
3573 return; // Not a key or a motion
3574 }
3575
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003576 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003577 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003578 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003579 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003580 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003581 continue; // Skip windows that receive ACTION_OUTSIDE
3582 }
3583
3584 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003585 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003586 if (connection == nullptr) {
3587 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003588 }
3589 newConnectionTokens.insert(std::move(token));
3590 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003591 if (target.windowHandle) {
3592 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3593 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003594 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003595
3596 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3597 REQUIRES(mLock) {
3598 scoped_unlock unlock(mLock);
3599 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3600 };
3601 postCommandLocked(std::move(command));
3602
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003603 if (newConnectionTokens == mInteractionConnectionTokens) {
3604 return; // no change
3605 }
3606 mInteractionConnectionTokens = newConnectionTokens;
3607
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003608 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003609 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003610 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003611 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003612 std::string message = "Interaction with: " + targetList;
3613 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003614 message += "<none>";
3615 }
3616 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3617}
3618
chaviwfd6d3512019-03-25 13:23:49 -07003619void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003620 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003621 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003622 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3623 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003624 return;
3625 }
3626
Vishnu Nairc519ff72021-01-21 08:23:08 -08003627 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003628 if (focusedToken == token) {
3629 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003630 return;
3631 }
3632
Prabir Pradhancef936d2021-07-21 16:17:52 +00003633 auto command = [this, token]() REQUIRES(mLock) {
3634 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003635 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003636 };
3637 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638}
3639
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003640status_t InputDispatcher::publishMotionEvent(Connection& connection,
3641 DispatchEntry& dispatchEntry) const {
3642 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3643 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3644
3645 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003646 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003647
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003648 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003649 // Set the X and Y offset and X and Y scale depending on the input source.
3650 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003651 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003652 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3653 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003654 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003655 scaledCoords[i] = motionEntry.pointerCoords[i];
3656 // Don't apply window scale here since we don't want scale to affect raw
3657 // coordinates. The scale will be sent back to the client and applied
3658 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003659 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003660 }
3661 usingCoords = scaledCoords;
3662 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003663 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003664 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003665 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003666 scaledCoords[i].clear();
3667 }
3668 usingCoords = scaledCoords;
3669 }
3670
3671 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3672
3673 // Publish the motion event.
3674 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003675 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3676 motionEntry.source, motionEntry.displayId, std::move(hmac),
3677 motionEntry.action, motionEntry.actionButton,
3678 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3679 motionEntry.metaState, motionEntry.buttonState,
3680 motionEntry.classification, dispatchEntry.transform,
3681 motionEntry.xPrecision, motionEntry.yPrecision,
3682 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3683 dispatchEntry.rawTransform, motionEntry.downTime,
3684 motionEntry.eventTime, motionEntry.getPointerCount(),
3685 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003686}
3687
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003689 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003690 ATRACE_NAME_IF(ATRACE_ENABLED(),
3691 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3692 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003693 if (DEBUG_DISPATCH_CYCLE) {
3694 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003697 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003698 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003700 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003701 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
3703 // Publish the event.
3704 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3706 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003707 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003708 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3709 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
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 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003715 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003717 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3718 keyEntry.deviceId, keyEntry.source,
3719 keyEntry.displayId, std::move(hmac),
3720 keyEntry.action, dispatchEntry->resolvedFlags,
3721 keyEntry.keyCode, keyEntry.scanCode,
3722 keyEntry.metaState, keyEntry.repeatCount,
3723 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003724 if (mTracer) {
3725 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3726 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
3729
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003730 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003731 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003732 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3733 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003734 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003735 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003736 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003737 if (mTracer) {
3738 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3739 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003740 break;
3741 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003742
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003743 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003745 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003746 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003747 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003748 break;
3749 }
3750
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003751 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3752 const TouchModeEntry& touchModeEntry =
3753 static_cast<const TouchModeEntry&>(eventEntry);
3754 status = connection->inputPublisher
3755 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3756 touchModeEntry.inTouchMode);
3757
3758 break;
3759 }
3760
Prabir Pradhan99987712020-11-10 18:43:05 -08003761 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3762 const auto& captureEntry =
3763 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3764 status = connection->inputPublisher
3765 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003766 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003767 break;
3768 }
3769
arthurhungb89ccb02020-12-30 16:19:01 +08003770 case EventEntry::Type::DRAG: {
3771 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3772 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3773 dragEntry.id, dragEntry.x,
3774 dragEntry.y,
3775 dragEntry.isExiting);
3776 break;
3777 }
3778
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003779 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003780 case EventEntry::Type::DEVICE_RESET:
3781 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003782 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003783 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003784 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787
3788 // Check the result.
3789 if (status) {
3790 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003791 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 "This is unexpected because the wait queue is empty, so the pipe "
3794 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003795 "event to it, status=%s(%d)",
3796 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3797 status);
Harry Cutts33476232023-01-30 19:57:29 +00003798 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 } else {
3800 // Pipe is full and we are waiting for the app to finish process some events
3801 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003802 if (DEBUG_DISPATCH_CYCLE) {
3803 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3804 "waiting for the application to catch up",
3805 connection->getInputChannelName().c_str());
3806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808 } else {
3809 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003810 "status=%s(%d)",
3811 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3812 status);
Harry Cutts33476232023-01-30 19:57:29 +00003813 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
3815 return;
3816 }
3817
3818 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003819 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3820 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3821 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003822 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003823 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003824 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003825 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003826 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828}
3829
chaviw09c8d2d2020-08-24 15:48:26 -07003830std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3831 size_t size;
3832 switch (event.type) {
3833 case VerifiedInputEvent::Type::KEY: {
3834 size = sizeof(VerifiedKeyEvent);
3835 break;
3836 }
3837 case VerifiedInputEvent::Type::MOTION: {
3838 size = sizeof(VerifiedMotionEvent);
3839 break;
3840 }
3841 }
3842 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3843 return mHmacKeyManager.sign(start, size);
3844}
3845
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003846const std::array<uint8_t, 32> InputDispatcher::getSignature(
3847 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003848 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003849 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003850 // Only sign events up and down events as the purely move events
3851 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003852 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003853 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003854
3855 VerifiedMotionEvent verifiedEvent =
3856 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3857 verifiedEvent.actionMasked = actionMasked;
3858 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3859 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003860}
3861
3862const std::array<uint8_t, 32> InputDispatcher::getSignature(
3863 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3864 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3865 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003866 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003867}
3868
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003870 const std::shared_ptr<Connection>& connection,
3871 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003872 if (DEBUG_DISPATCH_CYCLE) {
3873 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3874 connection->getInputChannelName().c_str(), seq, toString(handled));
3875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003877 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 return;
3879 }
3880
3881 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003882 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3883 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3884 };
3885 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886}
3887
3888void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003889 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003890 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003891 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003892 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3893 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
3896 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003897 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003898 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003899 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003900 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
3902 // The connection appears to be unrecoverably broken.
3903 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003904 if (connection->status == Connection::Status::NORMAL) {
3905 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
3907 if (notify) {
3908 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003909 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3910 connection->getInputChannelName().c_str());
3911
3912 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003913 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003914 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003915 };
3916 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918 }
3919}
3920
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003921void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003922 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003923 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003924 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 }
3926}
3927
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003928void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003930 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932}
3933
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003934int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3935 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003936 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003937 if (connection == nullptr) {
3938 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3939 connectionToken.get(), events);
3940 return 0; // remove the callback
3941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003943 bool notify;
3944 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3945 if (!(events & ALOOPER_EVENT_INPUT)) {
3946 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3947 "events=0x%x",
3948 connection->getInputChannelName().c_str(), events);
3949 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
3951
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003952 nsecs_t currentTime = now();
3953 bool gotOne = false;
3954 status_t status = OK;
3955 for (;;) {
3956 Result<InputPublisher::ConsumerResponse> result =
3957 connection->inputPublisher.receiveConsumerResponse();
3958 if (!result.ok()) {
3959 status = result.error().code();
3960 break;
3961 }
3962
3963 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3964 const InputPublisher::Finished& finish =
3965 std::get<InputPublisher::Finished>(*result);
3966 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3967 finish.consumeTime);
3968 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003969 if (shouldReportMetricsForConnection(*connection)) {
3970 const InputPublisher::Timeline& timeline =
3971 std::get<InputPublisher::Timeline>(*result);
3972 mLatencyTracker
3973 .trackGraphicsLatency(timeline.inputEventId,
3974 connection->inputChannel->getConnectionToken(),
3975 std::move(timeline.graphicsTimeline));
3976 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003977 }
3978 gotOne = true;
3979 }
3980 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003981 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003982 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 return 1;
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 }
3986
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003987 notify = status != DEAD_OBJECT || !connection->monitor;
3988 if (notify) {
3989 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3990 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3991 status);
3992 }
3993 } else {
3994 // Monitor channels are never explicitly unregistered.
3995 // We do it automatically when the remote endpoint is closed so don't warn about them.
3996 const bool stillHaveWindowHandle =
3997 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3998 notify = !connection->monitor && stillHaveWindowHandle;
3999 if (notify) {
4000 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
4001 connection->getInputChannelName().c_str(), events);
4002 }
4003 }
4004
4005 // Remove the channel.
4006 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
4007 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008}
4009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004012 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00004013 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 }
4015}
4016
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004017void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004018 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004019 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004020 for (const Monitor& monitor : monitors) {
4021 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004022 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004023 }
4024}
4025
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004027 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004028 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004029 if (connection == nullptr) {
4030 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004032
4033 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034}
4035
4036void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004037 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004038 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 return;
4040 }
4041
4042 nsecs_t currentTime = now();
4043
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004044 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004045 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004047 if (cancelationEvents.empty()) {
4048 return;
4049 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004050
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004051 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4052 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004053 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004054 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004055 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004056 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004057
Arthur Hungb3307ee2021-10-14 10:57:37 +00004058 std::string reason = std::string("reason=").append(options.reason);
4059 android_log_event_list(LOGTAG_INPUT_CANCEL)
4060 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4061
hongzuo liu95785e22022-09-06 02:51:35 +00004062 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004063 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004064 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004065 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004066
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004067 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004068 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004069 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004070
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004071 switch (cancelationEventEntry->type) {
4072 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004073 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004074 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4075 ? std::make_optional(keyEntry.displayId)
4076 : std::nullopt;
4077 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004078 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4079 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004080 } else {
4081 targets.emplace_back(fallbackTarget);
4082 }
4083 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004084 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004086 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004087 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004088 const std::optional<int32_t> targetDisplay =
4089 motionEntry.displayId != ADISPLAY_ID_NONE
4090 ? std::make_optional(motionEntry.displayId)
4091 : std::nullopt;
4092 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004093 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004094 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004095 pointerIndex++) {
4096 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4097 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004098 if (mDragState && mDragState->dragWindow->getToken() == token &&
4099 pointerIds.test(mDragState->pointerId)) {
4100 LOG(INFO) << __func__
4101 << ": Canceling drag and drop because the pointers for the drag "
4102 "window are being canceled.";
4103 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4104 mDragState.reset();
4105 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004106 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4107 ftl::Flags<InputTarget::Flags>(), pointerIds,
4108 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004109 } else {
4110 targets.emplace_back(fallbackTarget);
4111 const auto it = mDisplayInfos.find(motionEntry.displayId);
4112 if (it != mDisplayInfos.end()) {
4113 targets.back().displayTransform = it->second.transform;
4114 targets.back().setDefaultPointerTransform(it->second.transform);
4115 }
4116 }
4117 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004118 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004120 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004121 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004122 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4123 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004124 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004125 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004126 break;
4127 }
4128 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004129 case EventEntry::Type::DEVICE_RESET:
4130 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004131 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004132 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004133 break;
4134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 }
4136
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004137 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004138 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004140
hongzuo liu95785e22022-09-06 02:51:35 +00004141 // If the outbound queue was previously empty, start the dispatch cycle going.
4142 if (wasEmpty && !connection->outboundQueue.empty()) {
4143 startDispatchCycleLocked(currentTime, connection);
4144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145}
4146
Svet Ganov5d3bc372020-01-26 23:11:07 -08004147void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004148 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004149 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004150 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004151 return;
4152 }
4153
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004154 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004155 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004156
4157 if (downEvents.empty()) {
4158 return;
4159 }
4160
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004161 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004162 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4163 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004165
chaviw98318de2021-05-19 16:45:23 -05004166 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004167 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004168
hongzuo liu95785e22022-09-06 02:51:35 +00004169 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004170 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004171 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004172 switch (downEventEntry->type) {
4173 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004174 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4175 if (windowHandle != nullptr) {
4176 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004177 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004178 pointerIndex++) {
4179 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4180 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004181 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4182 targetFlags, pointerIds, motionEntry.downTime,
4183 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004184 } else {
4185 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4186 .flags = targetFlags});
4187 const auto it = mDisplayInfos.find(motionEntry.displayId);
4188 if (it != mDisplayInfos.end()) {
4189 targets.back().displayTransform = it->second.transform;
4190 targets.back().setDefaultPointerTransform(it->second.transform);
4191 }
4192 }
4193 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004194 break;
4195 }
4196
4197 case EventEntry::Type::KEY:
4198 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004199 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004200 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004201 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004202 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004203 case EventEntry::Type::SENSOR:
4204 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004205 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004206 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004207 break;
4208 }
4209 }
4210
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004211 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004212 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004213 }
4214
hongzuo liu95785e22022-09-06 02:51:35 +00004215 // If the outbound queue was previously empty, start the dispatch cycle going.
4216 if (wasEmpty && !connection->outboundQueue.empty()) {
4217 startDispatchCycleLocked(downTime, connection);
4218 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004219}
4220
Arthur Hungc539dbb2022-12-08 07:45:36 +00004221void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4222 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4223 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004224 std::shared_ptr<Connection> wallpaperConnection =
4225 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004226 if (wallpaperConnection != nullptr) {
4227 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4228 }
4229 }
4230}
4231
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004232std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004233 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4234 nsecs_t splitDownTime) {
4235 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236
4237 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004238 std::vector<PointerProperties> splitPointerProperties;
4239 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004241 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 uint32_t splitPointerCount = 0;
4243
4244 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004247 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004249 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004251 splitPointerProperties.push_back(pointerProperties);
4252 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 splitPointerCount += 1;
4254 }
4255 }
4256
4257 if (splitPointerCount != pointerIds.count()) {
4258 // This is bad. We are missing some of the pointers that we expected to deliver.
4259 // Most likely this indicates that we received an ACTION_MOVE events that has
4260 // different pointer ids than we expected based on the previous ACTION_DOWN
4261 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4262 // in this way.
4263 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004264 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004265 "a broken sequence of pointer ids from the input device: %s",
4266 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004267 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004270 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4273 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004274 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004276 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004278 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 if (pointerIds.count() == 1) {
4280 // The first/last pointer went down/up.
4281 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004283 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4284 ? AMOTION_EVENT_ACTION_CANCEL
4285 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 } else {
4287 // A secondary pointer went down/up.
4288 uint32_t splitPointerIndex = 0;
4289 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4290 splitPointerIndex += 1;
4291 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 action = maskedAction |
4293 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295 } else {
4296 // An unrelated pointer changed.
4297 action = AMOTION_EVENT_ACTION_MOVE;
4298 }
4299 }
4300
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004301 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4302 logDispatchStateLocked();
4303 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4304 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4305 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004306 }
4307
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004308 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004309 ATRACE_NAME_IF(ATRACE_ENABLED(),
4310 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4311 ").",
4312 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004314 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4315 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004316 originalMotionEntry.deviceId, originalMotionEntry.source,
4317 originalMotionEntry.displayId,
4318 originalMotionEntry.policyFlags, action,
4319 originalMotionEntry.actionButton,
4320 originalMotionEntry.flags, originalMotionEntry.metaState,
4321 originalMotionEntry.buttonState,
4322 originalMotionEntry.classification,
4323 originalMotionEntry.edgeFlags,
4324 originalMotionEntry.xPrecision,
4325 originalMotionEntry.yPrecision,
4326 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004327 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004328 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 return splitMotionEntry;
4331}
4332
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004333void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4334 std::scoped_lock _l(mLock);
4335 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4336}
4337
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004338void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004339 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004340 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342
Antonio Kantekf16f2832021-09-28 04:39:20 +00004343 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004347 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004348 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 } // release lock
4351
4352 if (needWake) {
4353 mLooper->wake();
4354 }
4355}
4356
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004357void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004358 ALOGD_IF(debugInboundEventDetails(),
4359 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4360 ", deviceId=%d, source=%s, displayId=%" PRId32
4361 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4362 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004363 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4364 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4365 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004366 Result<void> keyCheck = validateKeyEvent(args.action);
4367 if (!keyCheck.ok()) {
4368 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 return;
4370 }
4371
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004372 uint32_t policyFlags = args.policyFlags;
4373 int32_t flags = args.flags;
4374 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004375 // InputDispatcher tracks and generates key repeats on behalf of
4376 // whatever notifies it, so repeatCount should always be set to 0
4377 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4379 policyFlags |= POLICY_FLAG_VIRTUAL;
4380 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 if (policyFlags & POLICY_FLAG_FUNCTION) {
4383 metaState |= AMETA_FUNCTION_ON;
4384 }
4385
4386 policyFlags |= POLICY_FLAG_TRUSTED;
4387
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004388 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004390 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4391 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4392 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
Michael Wright2b3c3302018-03-02 17:19:13 +00004394 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004395 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004396 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4397 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
Antonio Kantekf16f2832021-09-28 04:39:20 +00004401 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 { // acquire lock
4403 mLock.lock();
4404
4405 if (shouldSendKeyToInputFilterLocked(args)) {
4406 mLock.unlock();
4407
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004408 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004409 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 return; // event was consumed by the filter
4411 }
4412
4413 mLock.lock();
4414 }
4415
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004416 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004417 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4418 args.deviceId, args.source, args.displayId, policyFlags,
4419 args.action, flags, keyCode, args.scanCode, metaState,
4420 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004421 if (mTracer) {
4422 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004425 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 mLock.unlock();
4427 } // release lock
4428
4429 if (needWake) {
4430 mLooper->wake();
4431 }
4432}
4433
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004434bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 return mInputFilterEnabled;
4436}
4437
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004438void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004439 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004440 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004442 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4444 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004445 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4446 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4447 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4448 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4449 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004450 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004451 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4452 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004453 i, args.pointerProperties[i].id,
4454 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4455 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4456 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4457 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4458 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4459 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4460 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4461 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4462 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4463 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004466
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004467 Result<void> motionCheck =
4468 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4469 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004470 if (!motionCheck.ok()) {
4471 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4472 return;
4473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004475 if (DEBUG_VERIFY_EVENTS) {
4476 auto [it, _] =
4477 mVerifiersByDisplay.try_emplace(args.displayId,
4478 StringPrintf("display %" PRId32, args.displayId));
4479 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004480 it->second.processMovement(args.deviceId, args.source, args.action,
4481 args.getPointerCount(), args.pointerProperties.data(),
4482 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004483 if (!result.ok()) {
4484 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4485 }
4486 }
4487
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004488 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004490
4491 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004492 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4493 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004494 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4495 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498
Antonio Kantekf16f2832021-09-28 04:39:20 +00004499 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 { // acquire lock
4501 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004502 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4503 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4504 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004505 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004506 if (touchStateIt != mTouchStatesByDisplay.end()) {
4507 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004508 if (touchState.hasTouchingPointers(args.deviceId) ||
4509 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004510 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4511 }
4512 }
4513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
4515 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004516 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004517 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004518 displayTransform = it->second.transform;
4519 }
4520
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 mLock.unlock();
4522
4523 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004524 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4525 args.action, args.actionButton, args.flags, args.edgeFlags,
4526 args.metaState, args.buttonState, args.classification,
4527 displayTransform, args.xPrecision, args.yPrecision,
4528 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004529 args.downTime, args.eventTime, args.getPointerCount(),
4530 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
4532 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004533 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 return; // event was consumed by the filter
4535 }
4536
4537 mLock.lock();
4538 }
4539
4540 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004541 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004542 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4543 args.deviceId, args.source, args.displayId,
4544 policyFlags, args.action, args.actionButton,
4545 args.flags, args.metaState, args.buttonState,
4546 args.classification, args.edgeFlags, args.xPrecision,
4547 args.yPrecision, args.xCursorPosition,
4548 args.yCursorPosition, args.downTime,
4549 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004550 if (mTracer) {
4551 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004554 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4555 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004556 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004557 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004558 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4559 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4560 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004561 }
4562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004563 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 mLock.unlock();
4565 } // release lock
4566
4567 if (needWake) {
4568 mLooper->wake();
4569 }
4570}
4571
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004572void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004573 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004574 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4575 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 args.id, args.eventTime, args.deviceId, args.source,
4577 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004578 }
Chris Yef59a2f42020-10-16 12:55:26 -07004579
Antonio Kantekf16f2832021-09-28 04:39:20 +00004580 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004581 { // acquire lock
4582 mLock.lock();
4583
4584 // Just enqueue a new sensor event.
4585 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004586 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4587 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4588 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004589
4590 needWake = enqueueInboundEventLocked(std::move(newEntry));
4591 mLock.unlock();
4592 } // release lock
4593
4594 if (needWake) {
4595 mLooper->wake();
4596 }
4597}
4598
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004599void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004600 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004601 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4602 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004603 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004604 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004605}
4606
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004607bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004608 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609}
4610
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004611void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004612 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004613 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4614 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004615 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004618 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004620 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621}
4622
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004623void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004624 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004625 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4626 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628
Antonio Kantekf16f2832021-09-28 04:39:20 +00004629 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004631 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004633 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004634 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004635 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004636
4637 for (auto& [_, verifier] : mVerifiersByDisplay) {
4638 verifier.resetDevice(args.deviceId);
4639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 } // release lock
4641
4642 if (needWake) {
4643 mLooper->wake();
4644 }
4645}
4646
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004647void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004648 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004649 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4650 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004651 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004652
Antonio Kantekf16f2832021-09-28 04:39:20 +00004653 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004654 { // acquire lock
4655 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004656 auto entry =
4657 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004658 needWake = enqueueInboundEventLocked(std::move(entry));
4659 } // release lock
4660
4661 if (needWake) {
4662 mLooper->wake();
4663 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004664}
4665
Prabir Pradhan5735a322022-04-11 17:23:34 +00004666InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004667 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004668 InputEventInjectionSync syncMode,
4669 std::chrono::milliseconds timeout,
4670 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004671 Result<void> eventValidation = validateInputEvent(*event);
4672 if (!eventValidation.ok()) {
4673 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4674 return InputEventInjectionResult::FAILED;
4675 }
4676
Prabir Pradhan65613802023-02-22 23:36:58 +00004677 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004678 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4679 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4680 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4681 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004682 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004683 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
Prabir Pradhan5735a322022-04-11 17:23:34 +00004685 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004687 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004688 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4689 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4690 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4691 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4692 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004693 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004694 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004695 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004696 }
4697
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004698 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4699 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4700
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004701 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004703 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004704 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004705 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004706 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004707 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4708 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4709 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004710 int32_t keyCode = incomingKey.getKeyCode();
4711 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004712 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004713 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004714 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4715 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4716 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004718 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4719 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004720 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721
4722 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4723 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004724 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4726 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4727 std::to_string(t.duration().count()).c_str());
4728 }
4729 }
4730
4731 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004732 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004733 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4734 incomingKey.getEventTime(), resolvedDeviceId,
4735 incomingKey.getSource(), incomingKey.getDisplayId(),
4736 policyFlags, action, flags, keyCode,
4737 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004738 incomingKey.getRepeatCount(),
4739 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004740 if (mTracer) {
4741 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4742 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004743 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 }
4746
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004747 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004748 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004749 const bool isPointerEvent =
4750 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4751 // If a pointer event has no displayId specified, inject it to the default display.
4752 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4753 ? ADISPLAY_ID_DEFAULT
4754 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004755 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756
4757 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004758 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004759 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004760 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4761 motionEvent.getAction(), eventTime,
4762 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4764 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4765 std::to_string(t.duration().count()).c_str());
4766 }
4767 }
4768
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004769 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4770 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4771 }
4772
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004774 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004775 const size_t pointerCount = motionEvent.getPointerCount();
4776 const std::vector<PointerProperties>
4777 pointerProperties(motionEvent.getPointerProperties(),
4778 motionEvent.getPointerProperties() + pointerCount);
4779
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004780 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004782 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4783 *sampleEventTimes, resolvedDeviceId,
4784 motionEvent.getSource(), displayId, policyFlags,
4785 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004786 motionEvent.getActionButton(), flags,
4787 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004788 motionEvent.getButtonState(),
4789 motionEvent.getClassification(),
4790 motionEvent.getEdgeFlags(),
4791 motionEvent.getXPrecision(),
4792 motionEvent.getYPrecision(),
4793 motionEvent.getRawXCursorPosition(),
4794 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004795 motionEvent.getDownTime(), pointerProperties,
4796 std::vector<PointerCoords>(samplePointerCoords,
4797 samplePointerCoords +
4798 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004799 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004800 if (mTracer) {
4801 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4802 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004803 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004804 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004806 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004807 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004808 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4809 resolvedDeviceId, motionEvent.getSource(), displayId,
4810 policyFlags, motionEvent.getAction(),
4811 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004812 motionEvent.getMetaState(), motionEvent.getButtonState(),
4813 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4814 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4815 motionEvent.getRawXCursorPosition(),
4816 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4817 pointerProperties,
4818 std::vector<PointerCoords>(samplePointerCoords,
4819 samplePointerCoords +
4820 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004821 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4822 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004823 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004824 }
4825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004829 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004834 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004835 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004836 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004837 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004838 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004839 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
4841
4842 mLock.unlock();
4843
4844 if (needWake) {
4845 mLooper->wake();
4846 }
4847
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004848 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004850 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 if (syncMode == InputEventInjectionSync::NONE) {
4853 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 } else {
4855 for (;;) {
4856 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 break;
4859 }
4860
4861 nsecs_t remainingTimeout = endTime - now();
4862 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004863 if (DEBUG_INJECTION) {
4864 ALOGD("injectInputEvent - Timed out waiting for injection result "
4865 "to become available.");
4866 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004867 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 break;
4869 }
4870
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004871 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 }
4873
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004874 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4875 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004877 if (DEBUG_INJECTION) {
4878 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4879 injectionState->pendingForegroundDispatches);
4880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 nsecs_t remainingTimeout = endTime - now();
4882 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004883 if (DEBUG_INJECTION) {
4884 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4885 "dispatches to finish.");
4886 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004887 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 break;
4889 }
4890
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004891 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 }
4893 }
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 } // release lock
4896
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004897 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004898 LOG(INFO) << "injectInputEvent - Finished with result "
4899 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902 return injectionResult;
4903}
4904
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004905std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004906 std::array<uint8_t, 32> calculatedHmac;
4907 std::unique_ptr<VerifiedInputEvent> result;
4908 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004909 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004910 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4911 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4912 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004913 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004914 break;
4915 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004916 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004917 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4918 VerifiedMotionEvent verifiedMotionEvent =
4919 verifiedMotionEventFromMotionEvent(motionEvent);
4920 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004921 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004922 break;
4923 }
4924 default: {
4925 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4926 return nullptr;
4927 }
4928 }
4929 if (calculatedHmac == INVALID_HMAC) {
4930 return nullptr;
4931 }
tyiu1573a672023-02-21 22:38:32 +00004932 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004933 return nullptr;
4934 }
4935 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004936}
4937
Prabir Pradhan24047542023-11-02 17:14:59 +00004938void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004939 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004940 if (!entry.injectionState) {
4941 // Not an injected event.
4942 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004944
4945 InjectionState& injectionState = *entry.injectionState;
4946 if (DEBUG_INJECTION) {
4947 LOG(INFO) << "Setting input event injection result to "
4948 << ftl::enum_string(injectionResult);
4949 }
4950
4951 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4952 // Log the outcome since the injector did not wait for the injection result.
4953 switch (injectionResult) {
4954 case InputEventInjectionResult::SUCCEEDED:
4955 ALOGV("Asynchronous input event injection succeeded.");
4956 break;
4957 case InputEventInjectionResult::TARGET_MISMATCH:
4958 ALOGV("Asynchronous input event injection target mismatch.");
4959 break;
4960 case InputEventInjectionResult::FAILED:
4961 ALOGW("Asynchronous input event injection failed.");
4962 break;
4963 case InputEventInjectionResult::TIMED_OUT:
4964 ALOGW("Asynchronous input event injection timed out.");
4965 break;
4966 case InputEventInjectionResult::PENDING:
4967 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4968 break;
4969 }
4970 }
4971
4972 injectionState.injectionResult = injectionResult;
4973 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974}
4975
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004976void InputDispatcher::transformMotionEntryForInjectionLocked(
4977 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004978 // Input injection works in the logical display coordinate space, but the input pipeline works
4979 // display space, so we need to transform the injected events accordingly.
4980 const auto it = mDisplayInfos.find(entry.displayId);
4981 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004982 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004983
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004984 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4985 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4986 const vec2 cursor =
4987 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4988 {entry.xCursorPosition, entry.yCursorPosition});
4989 entry.xCursorPosition = cursor.x;
4990 entry.yCursorPosition = cursor.y;
4991 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004992 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004993 entry.pointerCoords[i] =
4994 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4995 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004996 }
4997}
4998
Prabir Pradhan24047542023-11-02 17:14:59 +00004999void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005000 if (entry.injectionState) {
5001 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 }
5003}
5004
Prabir Pradhan24047542023-11-02 17:14:59 +00005005void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005006 if (entry.injectionState) {
5007 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00005009 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005010 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012 }
5013}
5014
chaviw98318de2021-05-19 16:45:23 -05005015const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005016 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005017 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005018 auto it = mWindowHandlesByDisplay.find(displayId);
5019 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005020}
5021
chaviw98318de2021-05-19 16:45:23 -05005022sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005023 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005024 if (windowHandleToken == nullptr) {
5025 return nullptr;
5026 }
5027
Prabir Pradhan16463382023-10-12 23:03:19 +00005028 if (!displayId) {
5029 // Look through all displays.
5030 for (auto& it : mWindowHandlesByDisplay) {
5031 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5032 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5033 if (windowHandle->getToken() == windowHandleToken) {
5034 return windowHandle;
5035 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005038 return nullptr;
5039 }
5040
Prabir Pradhan16463382023-10-12 23:03:19 +00005041 // Only look through the requested display.
5042 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005043 if (windowHandle->getToken() == windowHandleToken) {
5044 return windowHandle;
5045 }
5046 }
5047 return nullptr;
5048}
5049
chaviw98318de2021-05-19 16:45:23 -05005050sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5051 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005052 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005053 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5054 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005055 if (handle->getId() == windowHandle->getId() &&
5056 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005057 if (windowHandle->getInfo()->displayId != it.first) {
5058 ALOGE("Found window %s in display %" PRId32
5059 ", but it should belong to display %" PRId32,
5060 windowHandle->getName().c_str(), it.first,
5061 windowHandle->getInfo()->displayId);
5062 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005063 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 }
5066 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005067 return nullptr;
5068}
5069
chaviw98318de2021-05-19 16:45:23 -05005070sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005071 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5072 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073}
5074
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005075ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5076 auto displayInfoIt = mDisplayInfos.find(displayId);
5077 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5078 : kIdentityTransform;
5079}
5080
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005081bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5082 const MotionEntry& motionEntry) const {
5083 const WindowInfo& info = *window->getInfo();
5084
5085 // Skip spy window targets that are not valid for targeted injection.
5086 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005087 return false;
5088 }
5089
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005090 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5091 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5092 return false;
5093 }
5094
5095 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5096 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5097 window->getName().c_str());
5098 return false;
5099 }
5100
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005101 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005102 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005103 ALOGW("Not sending touch to %s because there's no corresponding connection",
5104 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005105 return false;
5106 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005107
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005108 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005109 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005110 return false;
5111 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005112
5113 // Drop events that can't be trusted due to occlusion
5114 const auto [x, y] = resolveTouchedPosition(motionEntry);
5115 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5116 if (!isTouchTrustedLocked(occlusionInfo)) {
5117 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005118 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005119 for (const auto& log : occlusionInfo.debugInfo) {
5120 ALOGD("%s", log.c_str());
5121 }
5122 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005123 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5124 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005125 return false;
5126 }
5127
5128 // Drop touch events if requested by input feature
5129 if (shouldDropInput(motionEntry, window)) {
5130 return false;
5131 }
5132
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005133 // Ignore touches if stylus is down anywhere on screen
5134 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5135 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5136 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5137 return false;
5138 }
5139
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005140 return true;
5141}
5142
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005143std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5144 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005145 auto connectionIt = mConnectionsByToken.find(token);
5146 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005147 return nullptr;
5148 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005149 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005150}
5151
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005152void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005153 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5154 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005155 // Remove all handles on a display if there are no windows left.
5156 mWindowHandlesByDisplay.erase(displayId);
5157 return;
5158 }
5159
5160 // Since we compare the pointer of input window handles across window updates, we need
5161 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005162 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5163 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5164 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005165 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005166 }
5167
chaviw98318de2021-05-19 16:45:23 -05005168 std::vector<sp<WindowInfoHandle>> newHandles;
5169 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005170 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005171 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005172 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005173 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005174 const bool canReceiveInput =
5175 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5176 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005177 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005178 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005179 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005180 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005181 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005182 }
5183
5184 if (info->displayId != displayId) {
5185 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5186 handle->getName().c_str(), displayId, info->displayId);
5187 continue;
5188 }
5189
Robert Carredd13602020-04-13 17:24:34 -07005190 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5191 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005192 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005193 oldHandle->updateFrom(handle);
5194 newHandles.push_back(oldHandle);
5195 } else {
5196 newHandles.push_back(handle);
5197 }
5198 }
5199
5200 // Insert or replace
5201 mWindowHandlesByDisplay[displayId] = newHandles;
5202}
5203
Arthur Hungb92218b2018-08-14 12:00:21 +08005204/**
5205 * Called from InputManagerService, update window handle list by displayId that can receive input.
5206 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5207 * If set an empty list, remove all handles from the specific display.
5208 * For focused handle, check if need to change and send a cancel event to previous one.
5209 * For removed handle, check if need to send a cancel event if already in touch.
5210 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005211void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005212 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005213 if (DEBUG_FOCUS) {
5214 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005215 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005216 windowList += iwh->getName() + " ";
5217 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005218 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220
Prabir Pradhand65552b2021-10-07 11:23:50 -07005221 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005222 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005223 const WindowInfo& info = *window->getInfo();
5224
5225 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005226 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005227 if (noInputWindow && window->getToken() != nullptr) {
5228 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5229 window->getName().c_str());
5230 window->releaseChannel();
5231 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005232
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005233 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005234 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5235 !info.inputConfig.test(
5236 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005237 "%s has feature SPY, but is not a trusted overlay.",
5238 window->getName().c_str());
5239
Prabir Pradhand65552b2021-10-07 11:23:50 -07005240 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005241 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5242 !info.inputConfig.test(
5243 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005244 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5245 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005246 }
5247
Arthur Hung72d8dc32020-03-28 00:48:39 +00005248 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005249 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
chaviw98318de2021-05-19 16:45:23 -05005251 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005252
chaviw98318de2021-05-19 16:45:23 -05005253 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005254
Vishnu Nairc519ff72021-01-21 08:23:08 -08005255 std::optional<FocusResolver::FocusChanges> changes =
5256 mFocusResolver.setInputWindows(displayId, windowHandles);
5257 if (changes) {
5258 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005261 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5262 mTouchStatesByDisplay.find(displayId);
5263 if (stateIt != mTouchStatesByDisplay.end()) {
5264 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005265 for (size_t i = 0; i < state.windows.size();) {
5266 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005267 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005268 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5269 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005270 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005271 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5272 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005273 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005274 "touched window was removed");
5275 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005276 // Since we are about to drop the touch, cancel the events for the wallpaper as
5277 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005278 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005279 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5280 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005281 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005282 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005285 state.windows.erase(state.windows.begin() + i);
5286 } else {
5287 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289 }
arthurhungb89ccb02020-12-30 16:19:01 +08005290
arthurhung6d4bed92021-03-17 11:59:33 +08005291 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005292 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005293 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005294 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005295 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005296 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5297 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005298 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005299 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005300 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005301
Arthur Hung72d8dc32020-03-28 00:48:39 +00005302 // Release information for windows that are no longer present.
5303 // This ensures that unused input channels are released promptly.
5304 // Otherwise, they might stick around until the window handle is destroyed
5305 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005306 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005307 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005308 if (DEBUG_FOCUS) {
5309 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005310 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005311 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005312 }
chaviw291d88a2019-02-14 10:33:58 -08005313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314}
5315
5316void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005317 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005318 if (DEBUG_FOCUS) {
5319 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5320 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5321 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005322 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005323 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005324 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 } // release lock
5326
5327 // Wake up poll loop since it may need to make new input dispatching choices.
5328 mLooper->wake();
5329}
5330
Vishnu Nair599f1412021-06-21 10:39:58 -07005331void InputDispatcher::setFocusedApplicationLocked(
5332 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5333 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5334 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5335
5336 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5337 return; // This application is already focused. No need to wake up or change anything.
5338 }
5339
5340 // Set the new application handle.
5341 if (inputApplicationHandle != nullptr) {
5342 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5343 } else {
5344 mFocusedApplicationHandlesByDisplay.erase(displayId);
5345 }
5346
5347 // No matter what the old focused application was, stop waiting on it because it is
5348 // no longer focused.
5349 resetNoFocusedWindowTimeoutLocked();
5350}
5351
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005352void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5353 if (interval.count() < 0) {
5354 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5355 }
5356 std::scoped_lock _l(mLock);
5357 mMinTimeBetweenUserActivityPokes = interval;
5358}
5359
Tiger Huang721e26f2018-07-24 22:26:19 +08005360/**
5361 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5362 * the display not specified.
5363 *
5364 * We track any unreleased events for each window. If a window loses the ability to receive the
5365 * released event, we will send a cancel event to it. So when the focused display is changed, we
5366 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5367 * display. The display-specified events won't be affected.
5368 */
5369void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005370 if (DEBUG_FOCUS) {
5371 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5372 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005373 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005374 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005375
5376 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005377 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005378 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005379 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005380 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005381 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005382 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005383 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005384 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005385 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005386 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5388 }
5389 }
5390 mFocusedDisplayId = displayId;
5391
Chris Ye3c2d6f52020-08-09 10:39:48 -07005392 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005393 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005394 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005395
Vishnu Nairad321cd2020-08-20 16:40:21 -07005396 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005397 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005398 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005399 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005400 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 }
5402 }
5403 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005404 } // release lock
5405
5406 // Wake up poll loop since it may need to make new input dispatching choices.
5407 mLooper->wake();
5408}
5409
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005411 if (DEBUG_FOCUS) {
5412 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414
5415 bool changed;
5416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
5419 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5420 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005421 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423
5424 if (mDispatchEnabled && !enabled) {
5425 resetAndDropEverythingLocked("dispatcher is being disabled");
5426 }
5427
5428 mDispatchEnabled = enabled;
5429 mDispatchFrozen = frozen;
5430 changed = true;
5431 } else {
5432 changed = false;
5433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 } // release lock
5435
5436 if (changed) {
5437 // Wake up poll loop since it may need to make new input dispatching choices.
5438 mLooper->wake();
5439 }
5440}
5441
5442void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005443 if (DEBUG_FOCUS) {
5444 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446
5447 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005448 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
5450 if (mInputFilterEnabled == enabled) {
5451 return;
5452 }
5453
5454 mInputFilterEnabled = enabled;
5455 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5456 } // release lock
5457
5458 // Wake up poll loop since there might be work to do to drop everything.
5459 mLooper->wake();
5460}
5461
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005462bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005463 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005464 bool needWake = false;
5465 {
5466 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005467 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005468 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005469 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005470 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5471 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005472 mTouchModePerDisplay.count(displayId) == 0
5473 ? "not set"
5474 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5475
Antonio Kantek15beb512022-06-13 22:35:41 +00005476 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5477 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005478 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005479 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005480 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005481 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5482 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005483 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005484 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005485 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005486 return false;
5487 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005488 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005489 mTouchModePerDisplay[displayId] = inTouchMode;
5490 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5491 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005492 needWake = enqueueInboundEventLocked(std::move(entry));
5493 } // release lock
5494
5495 if (needWake) {
5496 mLooper->wake();
5497 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005498 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005499}
5500
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005501bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005502 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5503 if (focusedToken == nullptr) {
5504 return false;
5505 }
5506 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5507 return isWindowOwnedBy(windowHandle, pid, uid);
5508}
5509
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005510bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005511 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5512 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5513 const sp<WindowInfoHandle> windowHandle =
5514 getWindowHandleLocked(connectionToken);
5515 return isWindowOwnedBy(windowHandle, pid, uid);
5516 }) != mInteractionConnectionTokens.end();
5517}
5518
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005519void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5520 if (opacity < 0 || opacity > 1) {
5521 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5522 return;
5523 }
5524
5525 std::scoped_lock lock(mLock);
5526 mMaximumObscuringOpacityForTouch = opacity;
5527}
5528
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005529std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5530InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005531 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5532 for (TouchedWindow& w : state.windows) {
5533 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005534 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005535 }
5536 }
5537 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005538 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005539}
5540
arthurhungb89ccb02020-12-30 16:19:01 +08005541bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5542 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005543 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005544 if (DEBUG_FOCUS) {
5545 ALOGD("Trivial transfer to same window.");
5546 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005547 return true;
5548 }
5549
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005551 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552
Arthur Hungabbb9d82021-09-01 14:52:30 +00005553 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005554 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005555
Arthur Hungabbb9d82021-09-01 14:52:30 +00005556 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005557 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 return false;
5559 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005560 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5561 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005562 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5563 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005564 return false;
5565 }
5566 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005567
Arthur Hungabbb9d82021-09-01 14:52:30 +00005568 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5569 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005570 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005571 return false;
5572 }
5573
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005574 if (DEBUG_FOCUS) {
5575 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005576 touchedWindow->windowHandle->getName().c_str(),
5577 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 }
5579
Arthur Hungabbb9d82021-09-01 14:52:30 +00005580 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005581 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005582 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005583 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005584 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585
Arthur Hungabbb9d82021-09-01 14:52:30 +00005586 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005587 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005588 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005589 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005590 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005591 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005592 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005593 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005594 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595
Arthur Hungabbb9d82021-09-01 14:52:30 +00005596 // Store the dragging window.
5597 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005598 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005599 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5600 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005601 return false;
5602 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005603 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005604 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005605 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 }
5607
Arthur Hungabbb9d82021-09-01 14:52:30 +00005608 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005609 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5610 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005611 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005612 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005613 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5614 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005616 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5617 newTargetFlags);
5618
5619 // Check if the wallpaper window should deliver the corresponding event.
5620 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005621 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 } // release lock
5624
5625 // Wake up poll loop since it may need to make new input dispatching choices.
5626 mLooper->wake();
5627 return true;
5628}
5629
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005630/**
5631 * Get the touched foreground window on the given display.
5632 * Return null if there are no windows touched on that display, or if more than one foreground
5633 * window is being touched.
5634 */
5635sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5636 auto stateIt = mTouchStatesByDisplay.find(displayId);
5637 if (stateIt == mTouchStatesByDisplay.end()) {
5638 ALOGI("No touch state on display %" PRId32, displayId);
5639 return nullptr;
5640 }
5641
5642 const TouchState& state = stateIt->second;
5643 sp<WindowInfoHandle> touchedForegroundWindow;
5644 // If multiple foreground windows are touched, return nullptr
5645 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005646 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005647 if (touchedForegroundWindow != nullptr) {
5648 ALOGI("Two or more foreground windows: %s and %s",
5649 touchedForegroundWindow->getName().c_str(),
5650 window.windowHandle->getName().c_str());
5651 return nullptr;
5652 }
5653 touchedForegroundWindow = window.windowHandle;
5654 }
5655 }
5656 return touchedForegroundWindow;
5657}
5658
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005659// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005660bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005661 sp<IBinder> fromToken;
5662 { // acquire lock
5663 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005664 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005665 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005666 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5667 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005668 return false;
5669 }
5670
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005671 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5672 if (from == nullptr) {
5673 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5674 return false;
5675 }
5676
5677 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005678 } // release lock
5679
5680 return transferTouchFocus(fromToken, destChannelToken);
5681}
5682
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005684 if (DEBUG_FOCUS) {
5685 ALOGD("Resetting and dropping all events (%s).", reason);
5686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687
Michael Wrightfb04fd52022-11-24 22:31:11 +00005688 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 synthesizeCancelationEventsForAllConnectionsLocked(options);
5690
5691 resetKeyRepeatLocked();
5692 releasePendingEventLocked();
5693 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005694 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005696 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005697 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698}
5699
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005700void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005701 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 dumpDispatchStateLocked(dump);
5703
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005704 std::istringstream stream(dump);
5705 std::string line;
5706
5707 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005708 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 }
5710}
5711
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005712std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005713 std::string dump;
5714
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005715 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5716 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005717
5718 std::string windowName = "None";
5719 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005720 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005721 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5722 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5723 : "token has capture without window";
5724 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005725 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005726
5727 return dump;
5728}
5729
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005730void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005731 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5732 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5733 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005734 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735
Tiger Huang721e26f2018-07-24 22:26:19 +08005736 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5737 dump += StringPrintf(INDENT "FocusedApplications:\n");
5738 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5739 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005740 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005741 const std::chrono::duration timeout =
5742 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005743 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005744 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005745 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005748 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005750
Vishnu Nairc519ff72021-01-21 08:23:08 -08005751 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005752 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005754 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005755 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005756 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005757 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5758 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
5760 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005761 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763
arthurhung6d4bed92021-03-17 11:59:33 +08005764 if (mDragState) {
5765 dump += StringPrintf(INDENT "DragState:\n");
5766 mDragState->dump(dump, INDENT2);
5767 }
5768
Arthur Hungb92218b2018-08-14 12:00:21 +08005769 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005770 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5771 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5772 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5773 const auto& displayInfo = it->second;
5774 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5775 displayInfo.logicalHeight);
5776 displayInfo.transform.dump(dump, "transform", INDENT4);
5777 } else {
5778 dump += INDENT2 "No DisplayInfo found!\n";
5779 }
5780
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005781 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005782 dump += INDENT2 "Windows:\n";
5783 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005784 dump += StringPrintf(INDENT3 "%zu: %s", i,
5785 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005786 }
5787 } else {
5788 dump += INDENT2 "Windows: <none>\n";
5789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005792 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 }
5794
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005795 if (!mGlobalMonitorsByDisplay.empty()) {
5796 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5797 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005798 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005801 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
5803
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005804 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805
5806 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005807 if (!mRecentQueue.empty()) {
5808 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005809 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005810 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005811 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005812 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 }
5814 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005815 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816 }
5817
5818 // Dump event currently being dispatched.
5819 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005820 dump += INDENT "PendingEvent:\n";
5821 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005822 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005823 dump += StringPrintf(", age=%" PRId64 "ms\n",
5824 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005826 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 }
5828
5829 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005830 if (!mInboundQueue.empty()) {
5831 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005832 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005833 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005834 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005835 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 }
5837 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005838 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 }
5840
Prabir Pradhancef936d2021-07-21 16:17:52 +00005841 if (!mCommandQueue.empty()) {
5842 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5843 } else {
5844 dump += INDENT "CommandQueue: <empty>\n";
5845 }
5846
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005847 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005848 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005849 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005850 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005851 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005852 connection->inputChannel->getFd().get(),
5853 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005854 connection->getWindowName().c_str(),
5855 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005856 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005858 if (!connection->outboundQueue.empty()) {
5859 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5860 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005861 dump += dumpQueue(connection->outboundQueue, currentTime);
5862
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005864 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865 }
5866
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005867 if (!connection->waitQueue.empty()) {
5868 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5869 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005870 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005872 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005874 std::string inputStateDump = streamableToString(connection->inputState);
5875 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005876 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005877 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
5880 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005881 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 }
5883
Antonio Kantek15beb512022-06-13 22:35:41 +00005884 if (!mTouchModePerDisplay.empty()) {
5885 dump += INDENT "TouchModePerDisplay:\n";
5886 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5887 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5888 std::to_string(touchMode).c_str());
5889 }
5890 } else {
5891 dump += INDENT "TouchModePerDisplay: <none>\n";
5892 }
5893
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005894 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005895 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5896 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5897 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005898 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005899 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005900 dump += INDENT "InputTracer: ";
5901 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902}
5903
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005904void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005905 const size_t numMonitors = monitors.size();
5906 for (size_t i = 0; i < numMonitors; i++) {
5907 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005908 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005909 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5910 dump += "\n";
5911 }
5912}
5913
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005914class LooperEventCallback : public LooperCallback {
5915public:
5916 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5917 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5918
5919private:
5920 std::function<int(int events)> mCallback;
5921};
5922
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005923Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005924 if (DEBUG_CHANNEL_CREATION) {
5925 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005928 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005929 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005930 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005931
5932 if (result) {
5933 return base::Error(result) << "Failed to open input channel pair with name " << name;
5934 }
5935
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005937 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005938 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005939 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005940 std::shared_ptr<Connection> connection =
5941 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5942 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005944 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5945 ALOGE("Created a new connection, but the token %p is already known", token.get());
5946 }
5947 mConnectionsByToken.emplace(token, connection);
5948
5949 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5950 this, std::placeholders::_1, token);
5951
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005952 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005953 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 } // release lock
5955
5956 // Wake the looper because some connections have changed.
5957 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005958 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959}
5960
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005961Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005962 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005963 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005964 std::shared_ptr<InputChannel> serverChannel;
5965 std::unique_ptr<InputChannel> clientChannel;
5966 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5967 if (result) {
5968 return base::Error(result) << "Failed to open input channel pair with name " << name;
5969 }
5970
Michael Wright3dd60e22019-03-27 22:06:44 +00005971 { // acquire lock
5972 std::scoped_lock _l(mLock);
5973
5974 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005975 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5976 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 }
5978
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005979 std::shared_ptr<Connection> connection =
5980 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005981 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005982 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005983
5984 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5985 ALOGE("Created a new connection, but the token %p is already known", token.get());
5986 }
5987 mConnectionsByToken.emplace(token, connection);
5988 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5989 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005990
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005991 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005992
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005993 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005994 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005995 }
Garfield Tan15601662020-09-22 15:32:38 -07005996
Michael Wright3dd60e22019-03-27 22:06:44 +00005997 // Wake the looper because some connections have changed.
5998 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005999 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00006000}
6001
Garfield Tan15601662020-09-22 15:32:38 -07006002status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006004 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005
Harry Cutts33476232023-01-30 19:57:29 +00006006 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 if (status) {
6008 return status;
6009 }
6010 } // release lock
6011
6012 // Wake the poll loop because removing the connection may have changed the current
6013 // synchronization state.
6014 mLooper->wake();
6015 return OK;
6016}
6017
Garfield Tan15601662020-09-22 15:32:38 -07006018status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6019 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006020 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006021 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006022 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023 return BAD_VALUE;
6024 }
6025
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006026 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006027
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006029 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 }
6031
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006032 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033
6034 nsecs_t currentTime = now();
6035 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6036
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006037 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 return OK;
6039}
6040
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006041void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006042 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6043 auto& [displayId, monitors] = *it;
6044 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6045 return monitor.inputChannel->getConnectionToken() == connectionToken;
6046 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006047
Michael Wright3dd60e22019-03-27 22:06:44 +00006048 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006049 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006050 } else {
6051 ++it;
6052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
6054}
6055
Michael Wright3dd60e22019-03-27 22:06:44 +00006056status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006057 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006058 return pilferPointersLocked(token);
6059}
Michael Wright3dd60e22019-03-27 22:06:44 +00006060
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006061status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006062 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6063 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006064 LOG(WARNING)
6065 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006066 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006067 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006068
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006069 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006070 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006071 LOG(WARNING)
6072 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6073 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006074 return BAD_VALUE;
6075 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006076 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006077 if (deviceIds.empty()) {
6078 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006079 return BAD_VALUE;
6080 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006081
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006082 for (const DeviceId deviceId : deviceIds) {
6083 TouchState& state = *statePtr;
6084 TouchedWindow& window = *windowPtr;
6085 // Send cancel events to all the input channels we're stealing from.
6086 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6087 "input channel stole pointer stream");
6088 options.deviceId = deviceId;
6089 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006090 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6091 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006092 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006093
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006094 std::string canceledWindows;
6095 for (const TouchedWindow& w : state.windows) {
6096 const std::shared_ptr<InputChannel> channel =
6097 getInputChannelLocked(w.windowHandle->getToken());
6098 if (channel != nullptr && channel->getConnectionToken() != token) {
6099 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6100 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6101 canceledWindows += channel->getName();
6102 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006103 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006104 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6105 LOG(INFO) << "Channel " << requestingChannel->getName()
6106 << " is stealing input gesture for device " << deviceId << " from "
6107 << canceledWindows;
6108
6109 // Prevent the gesture from being sent to any other windows.
6110 // This only blocks relevant pointers to be sent to other windows
6111 window.addPilferingPointers(deviceId, pointerIds);
6112
6113 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006114 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006115 return OK;
6116}
6117
Prabir Pradhan99987712020-11-10 18:43:05 -08006118void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6119 { // acquire lock
6120 std::scoped_lock _l(mLock);
6121 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006122 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006123 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6124 windowHandle != nullptr ? windowHandle->getName().c_str()
6125 : "token without window");
6126 }
6127
Vishnu Nairc519ff72021-01-21 08:23:08 -08006128 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006129 if (focusedToken != windowToken) {
6130 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6131 enabled ? "enable" : "disable");
6132 return;
6133 }
6134
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006135 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006136 ALOGW("Ignoring request to %s Pointer Capture: "
6137 "window has %s requested pointer capture.",
6138 enabled ? "enable" : "disable", enabled ? "already" : "not");
6139 return;
6140 }
6141
Christine Franksb768bb42021-11-29 12:11:31 -08006142 if (enabled) {
6143 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6144 mIneligibleDisplaysForPointerCapture.end(),
6145 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6146 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6147 return;
6148 }
6149 }
6150
Prabir Pradhan99987712020-11-10 18:43:05 -08006151 setPointerCaptureLocked(enabled);
6152 } // release lock
6153
6154 // Wake the thread to process command entries.
6155 mLooper->wake();
6156}
6157
Christine Franksb768bb42021-11-29 12:11:31 -08006158void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6159 { // acquire lock
6160 std::scoped_lock _l(mLock);
6161 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6162 if (!isEligible) {
6163 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6164 }
6165 } // release lock
6166}
6167
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006168std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006169 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006170 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006171 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006172 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006173 }
6174 }
6175 }
6176 return std::nullopt;
6177}
6178
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006179std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6180 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006181 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006182 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006183 }
6184
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006185 for (const auto& [token, connection] : mConnectionsByToken) {
6186 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006187 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 }
6189 }
Robert Carr4e670e52018-08-15 13:26:12 -07006190
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006191 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192}
6193
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006194std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006195 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006196 if (connection == nullptr) {
6197 return "<nullptr>";
6198 }
6199 return connection->getInputChannelName();
6200}
6201
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006202void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006203 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006204 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006205}
6206
Prabir Pradhancef936d2021-07-21 16:17:52 +00006207void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006208 const std::shared_ptr<Connection>& connection,
6209 uint32_t seq, bool handled,
6210 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006211 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006212 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006213
6214 { // Start critical section
6215 auto dispatchEntryIt =
6216 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6217 [seq](auto& e) { return e->seq == seq; });
6218 if (dispatchEntryIt == connection->waitQueue.end()) {
6219 return;
6220 }
6221
6222 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6223
6224 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6225 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6226 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6227 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6228 }
6229 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6230 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6231 connection->inputChannel->getConnectionToken(),
6232 dispatchEntry.deliveryTime, consumeTime, finishTime);
6233 }
6234
6235 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006236 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6237 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006238 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006239 }
6240 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241
6242 // Dequeue the event and start the next cycle.
6243 // Because the lock might have been released, it is possible that the
6244 // contents of the wait queue to have been drained, so we need to double-check
6245 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006246 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6247 [seq](auto& e) { return e->seq == seq; });
6248 if (entryIt != connection->waitQueue.end()) {
6249 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6250 connection->waitQueue.erase(entryIt);
6251
Prabir Pradhancef936d2021-07-21 16:17:52 +00006252 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6253 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6254 if (!connection->responsive) {
6255 connection->responsive = isConnectionResponsive(*connection);
6256 if (connection->responsive) {
6257 // The connection was unresponsive, and now it's responsive.
6258 processConnectionResponsiveLocked(*connection);
6259 }
6260 }
6261 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006262 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6263 const InputTarget target{.inputChannel = connection->inputChannel,
6264 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006265 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006266 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006267 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006268 }
6269
6270 // Start the next dispatch cycle for this connection.
6271 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272}
6273
Prabir Pradhancef936d2021-07-21 16:17:52 +00006274void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6275 const sp<IBinder>& newToken) {
6276 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6277 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006278 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006279 };
6280 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281}
6282
Prabir Pradhancef936d2021-07-21 16:17:52 +00006283void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6284 auto command = [this, token, x, y]() REQUIRES(mLock) {
6285 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006286 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287 };
6288 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006289}
6290
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006291void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006292 if (connection == nullptr) {
6293 LOG_ALWAYS_FATAL("Caller must check for nullness");
6294 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006295 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6296 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006298 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006299 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006300 return;
6301 }
6302 /**
6303 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6304 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6305 * has changed. This could cause newer entries to time out before the already dispatched
6306 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6307 * processes the events linearly. So providing information about the oldest entry seems to be
6308 * most useful.
6309 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006310 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6311 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006312 std::string reason =
6313 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006314 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006315 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006316 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006317 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006318 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006319
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006320 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6321
6322 // Stop waking up for events on this connection, it is already unresponsive
6323 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006324}
6325
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006326void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6327 std::string reason =
6328 StringPrintf("%s does not have a focused window", application->getName().c_str());
6329 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006330
Yabin Cui8eb9c552023-06-08 18:05:07 +00006331 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006332 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006333 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006334 };
6335 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006336}
6337
chaviw98318de2021-05-19 16:45:23 -05006338void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006339 const std::string& reason) {
6340 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6341 updateLastAnrStateLocked(windowLabel, reason);
6342}
6343
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006344void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6345 const std::string& reason) {
6346 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006347 updateLastAnrStateLocked(windowLabel, reason);
6348}
6349
6350void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6351 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006353 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 struct tm tm;
6355 localtime_r(&t, &tm);
6356 char timestr[64];
6357 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006358 mLastAnrState.clear();
6359 mLastAnrState += INDENT "ANR:\n";
6360 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006361 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6362 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006363 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364}
6365
Prabir Pradhancef936d2021-07-21 16:17:52 +00006366void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006367 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006368 const KeyEvent event = createKeyEvent(entry);
6369 nsecs_t delay = 0;
6370 { // release lock
6371 scoped_unlock unlock(mLock);
6372 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006373 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006374 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6375 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6376 std::to_string(t.duration().count()).c_str());
6377 }
6378 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379
6380 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006381 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006382 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006383 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006385 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006386 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388}
6389
Prabir Pradhancef936d2021-07-21 16:17:52 +00006390void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006391 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006392 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006393 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006394 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006395 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006396 };
6397 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006398}
6399
Prabir Pradhanedd96402022-02-15 01:46:16 -08006400void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006401 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006402 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006403 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006404 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006405 };
6406 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006407}
6408
6409/**
6410 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6411 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6412 * command entry to the command queue.
6413 */
6414void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6415 std::string reason) {
6416 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006417 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006418 if (connection.monitor) {
6419 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6420 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006421 pid = findMonitorPidByTokenLocked(connectionToken);
6422 } else {
6423 // The connection is a window
6424 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6425 reason.c_str());
6426 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6427 if (handle != nullptr) {
6428 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006429 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006430 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006431 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006432}
6433
6434/**
6435 * Tell the policy that a connection has become responsive so that it can stop ANR.
6436 */
6437void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6438 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006439 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006440 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006441 pid = findMonitorPidByTokenLocked(connectionToken);
6442 } else {
6443 // The connection is a window
6444 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6445 if (handle != nullptr) {
6446 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006447 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006448 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006449 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006450}
6451
Prabir Pradhan24047542023-11-02 17:14:59 +00006452std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006453 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006454 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006455 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006456 if (!handled) {
6457 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006458 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006459 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006460 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006463 // Get the fallback key state.
6464 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006465 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006466 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006467 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006468 connection->inputState.removeFallbackKey(originalKeyCode);
6469 }
6470
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006471 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006472 // If the application handles the original key for which we previously
6473 // generated a fallback or if the window is not a foreground window,
6474 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006475 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006476 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006477 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6478 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6479 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6480 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6481 keyEntry.policyFlags);
6482 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006483 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006484 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006485
6486 mLock.unlock();
6487
Prabir Pradhana41d2442023-04-20 21:30:40 +00006488 if (const auto unhandledKeyFallback =
6489 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6490 event, keyEntry.policyFlags);
6491 unhandledKeyFallback) {
6492 event = *unhandledKeyFallback;
6493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006494
6495 mLock.lock();
6496
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006497 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006498 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006499 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006500 "application handled the original non-fallback key "
6501 "or is no longer a foreground target, "
6502 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006503 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006506 connection->inputState.removeFallbackKey(originalKeyCode);
6507 }
6508 } else {
6509 // If the application did not handle a non-fallback key, first check
6510 // that we are in a good state to perform unhandled key event processing
6511 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006512 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006513 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006514 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6515 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6516 "since this is not an initial down. "
6517 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6518 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6519 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006520 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006523 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006524 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6525 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6526 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6527 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6528 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006529 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530
6531 mLock.unlock();
6532
Prabir Pradhana41d2442023-04-20 21:30:40 +00006533 bool fallback = false;
6534 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6535 event, keyEntry.policyFlags);
6536 fb) {
6537 fallback = true;
6538 event = *fb;
6539 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006540
6541 mLock.lock();
6542
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006543 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006544 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006545 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006546 }
6547
6548 // Latch the fallback keycode for this key on an initial down.
6549 // The fallback keycode cannot change at any other point in the lifecycle.
6550 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006552 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006553 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006554 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006555 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006556 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006557 }
6558
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006559 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006560
6561 // Cancel the fallback key if the policy decides not to send it anymore.
6562 // We will continue to dispatch the key to the policy but we will no
6563 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006564 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6565 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006566 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6567 if (fallback) {
6568 ALOGD("Unhandled key event: Policy requested to send key %d"
6569 "as a fallback for %d, but on the DOWN it had requested "
6570 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006571 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006572 } else {
6573 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6574 "but on the DOWN it had requested to send %d. "
6575 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006576 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006577 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006578 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579
Michael Wrightfb04fd52022-11-24 22:31:11 +00006580 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006581 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006582 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006583 synthesizeCancelationEventsForConnectionLocked(connection, options);
6584
6585 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006586 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006587 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006588 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006589 }
6590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6593 {
6594 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006595 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006596 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006597 for (const auto& [key, value] : fallbackKeys) {
6598 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006599 }
6600 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6601 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006602 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006603 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006604
6605 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006606 // Return the fallback key that we want dispatched to the channel.
6607 std::unique_ptr<KeyEntry> newEntry =
6608 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6609 event.getEventTime(), event.getDeviceId(),
6610 event.getSource(), event.getDisplayId(),
6611 keyEntry.policyFlags, keyEntry.action,
6612 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6613 *fallbackKeyCode, event.getScanCode(),
6614 event.getMetaState(), event.getRepeatCount(),
6615 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006616 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6617 ALOGD("Unhandled key event: Dispatching fallback key. "
6618 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006619 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006620 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006621 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006622 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6624 ALOGD("Unhandled key event: No fallback key.");
6625 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006626
6627 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006628 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006629 }
6630 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006631 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632}
6633
Michael Wrightd02c5b62014-02-10 15:10:22 -08006634void InputDispatcher::traceInboundQueueLengthLocked() {
6635 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006636 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637 }
6638}
6639
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006640void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006641 if (ATRACE_ENABLED()) {
6642 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006643 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6644 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006645 }
6646}
6647
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006648void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006649 if (ATRACE_ENABLED()) {
6650 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006651 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6652 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006653 }
6654}
6655
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006656void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006657 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006659 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006660 dumpDispatchStateLocked(dump);
6661
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006662 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006663 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006664 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006665 }
6666}
6667
6668void InputDispatcher::monitor() {
6669 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006670 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006671 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006672 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006673}
6674
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006675/**
6676 * Wake up the dispatcher and wait until it processes all events and commands.
6677 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6678 * this method can be safely called from any thread, as long as you've ensured that
6679 * the work you are interested in completing has already been queued.
6680 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006681bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006682 /**
6683 * Timeout should represent the longest possible time that a device might spend processing
6684 * events and commands.
6685 */
6686 constexpr std::chrono::duration TIMEOUT = 100ms;
6687 std::unique_lock lock(mLock);
6688 mLooper->wake();
6689 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6690 return result == std::cv_status::no_timeout;
6691}
6692
Vishnu Naire798b472020-07-23 13:52:21 -07006693/**
6694 * Sets focus to the window identified by the token. This must be called
6695 * after updating any input window handles.
6696 *
6697 * Params:
6698 * request.token - input channel token used to identify the window that should gain focus.
6699 * request.focusedToken - the token that the caller expects currently to be focused. If the
6700 * specified token does not match the currently focused window, this request will be dropped.
6701 * If the specified focused token matches the currently focused window, the call will succeed.
6702 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6703 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6704 * when requesting the focus change. This determines which request gets
6705 * precedence if there is a focus change request from another source such as pointer down.
6706 */
Vishnu Nair958da932020-08-21 17:12:37 -07006707void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6708 { // acquire lock
6709 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006710 std::optional<FocusResolver::FocusChanges> changes =
6711 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6712 if (changes) {
6713 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006714 }
6715 } // release lock
6716 // Wake up poll loop since it may need to make new input dispatching choices.
6717 mLooper->wake();
6718}
6719
Vishnu Nairc519ff72021-01-21 08:23:08 -08006720void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6721 if (changes.oldFocus) {
6722 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006723 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006724 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006725 "focus left window");
6726 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006727 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006728 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006729 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006730 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006731 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006732 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006733 }
6734
Prabir Pradhan99987712020-11-10 18:43:05 -08006735 // If a window has pointer capture, then it must have focus. We need to ensure that this
6736 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6737 // If the window loses focus before it loses pointer capture, then the window can be in a state
6738 // where it has pointer capture but not focus, violating the contract. Therefore we must
6739 // dispatch the pointer capture event before the focus event. Since focus events are added to
6740 // the front of the queue (above), we add the pointer capture event to the front of the queue
6741 // after the focus events are added. This ensures the pointer capture event ends up at the
6742 // front.
6743 disablePointerCaptureForcedLocked();
6744
Vishnu Nairc519ff72021-01-21 08:23:08 -08006745 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006746 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006747 }
6748}
Vishnu Nair958da932020-08-21 17:12:37 -07006749
Prabir Pradhan99987712020-11-10 18:43:05 -08006750void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006751 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006752 return;
6753 }
6754
6755 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6756
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006757 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006758 setPointerCaptureLocked(false);
6759 }
6760
6761 if (!mWindowTokenWithPointerCapture) {
6762 // No need to send capture changes because no window has capture.
6763 return;
6764 }
6765
6766 if (mPendingEvent != nullptr) {
6767 // Move the pending event to the front of the queue. This will give the chance
6768 // for the pending event to be dropped if it is a captured event.
6769 mInboundQueue.push_front(mPendingEvent);
6770 mPendingEvent = nullptr;
6771 }
6772
6773 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006774 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006775 mInboundQueue.push_front(std::move(entry));
6776}
6777
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006778void InputDispatcher::setPointerCaptureLocked(bool enable) {
6779 mCurrentPointerCaptureRequest.enable = enable;
6780 mCurrentPointerCaptureRequest.seq++;
6781 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006782 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006783 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006784 };
6785 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006786}
6787
Vishnu Nair599f1412021-06-21 10:39:58 -07006788void InputDispatcher::displayRemoved(int32_t displayId) {
6789 { // acquire lock
6790 std::scoped_lock _l(mLock);
6791 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006792 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006793 setFocusedApplicationLocked(displayId, nullptr);
6794 // Call focus resolver to clean up stale requests. This must be called after input windows
6795 // have been removed for the removed display.
6796 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006797 // Reset pointer capture eligibility, regardless of previous state.
6798 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006799 // Remove the associated touch mode state.
6800 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006801 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006802 } // release lock
6803
6804 // Wake up poll loop since it may need to make new input dispatching choices.
6805 mLooper->wake();
6806}
6807
Patrick Williamsd828f302023-04-28 17:52:08 -05006808void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006809 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6810 {
6811 // acquire lock
6812 std::scoped_lock _l(mLock);
6813 logDispatchStateLocked();
6814 }
6815 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6816 result.error().message().c_str());
6817 };
chaviw15fab6f2021-06-07 14:15:52 -05006818 // The listener sends the windows as a flattened array. Separate the windows by display for
6819 // more convenient parsing.
6820 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006821 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006822 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006823 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006824 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006825
6826 { // acquire lock
6827 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006828
6829 // Ensure that we have an entry created for all existing displays so that if a displayId has
6830 // no windows, we can tell that the windows were removed from the display.
6831 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6832 handlesPerDisplay[displayId];
6833 }
6834
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006835 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006836 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006837 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6838 }
6839
6840 for (const auto& [displayId, handles] : handlesPerDisplay) {
6841 setInputWindowsLocked(handles, displayId);
6842 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006843
6844 if (update.vsyncId < mWindowInfosVsyncId) {
6845 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6846 ", current update vsync id: %" PRId64,
6847 mWindowInfosVsyncId, update.vsyncId);
6848 }
6849 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006850 }
6851 // Wake up poll loop since it may need to make new input dispatching choices.
6852 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006853}
6854
Vishnu Nair062a8672021-09-03 16:07:44 -07006855bool InputDispatcher::shouldDropInput(
6856 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006857 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6858 (windowHandle->getInfo()->inputConfig.test(
6859 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006860 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006861 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6862 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006863 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006864 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006865 windowHandle->getInfo()->displayId);
6866 return true;
6867 }
6868 return false;
6869}
6870
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006871void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006872 const gui::WindowInfosUpdate& update) {
6873 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006874}
6875
Arthur Hungdfd528e2021-12-08 13:23:04 +00006876void InputDispatcher::cancelCurrentTouch() {
6877 {
6878 std::scoped_lock _l(mLock);
6879 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006880 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006881 "cancel current touch");
6882 synthesizeCancelationEventsForAllConnectionsLocked(options);
6883
6884 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006885 }
6886 // Wake up poll loop since there might be work to do.
6887 mLooper->wake();
6888}
6889
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006890void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6891 std::scoped_lock _l(mLock);
6892 mMonitorDispatchingTimeout = timeout;
6893}
6894
Arthur Hungc539dbb2022-12-08 07:45:36 +00006895void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6896 const sp<WindowInfoHandle>& oldWindowHandle,
6897 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006898 TouchState& state, int32_t deviceId,
6899 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006900 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006901 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006902 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6903 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6904 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6905 newWindowHandle->getInfo()->inputConfig.test(
6906 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6907 const sp<WindowInfoHandle> oldWallpaper =
6908 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6909 const sp<WindowInfoHandle> newWallpaper =
6910 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6911 if (oldWallpaper == newWallpaper) {
6912 return;
6913 }
6914
6915 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006916 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006917 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006918 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006919 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006920 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006921 }
6922
6923 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006924 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6925 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006926 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006927 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006928 }
6929}
6930
6931void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6932 ftl::Flags<InputTarget::Flags> newTargetFlags,
6933 const sp<WindowInfoHandle> fromWindowHandle,
6934 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006935 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006936 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006937 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6938 fromWindowHandle->getInfo()->inputConfig.test(
6939 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6940 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6941 toWindowHandle->getInfo()->inputConfig.test(
6942 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6943
6944 const sp<WindowInfoHandle> oldWallpaper =
6945 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6946 const sp<WindowInfoHandle> newWallpaper =
6947 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6948 if (oldWallpaper == newWallpaper) {
6949 return;
6950 }
6951
6952 if (oldWallpaper != nullptr) {
6953 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6954 "transferring touch focus to another window");
6955 state.removeWindowByToken(oldWallpaper->getToken());
6956 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6957 }
6958
6959 if (newWallpaper != nullptr) {
6960 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006961 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006962 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6963 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006964 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006965 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006966 std::shared_ptr<Connection> wallpaperConnection =
6967 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006968 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006969 std::shared_ptr<Connection> toConnection =
6970 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006971 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6972 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6973 wallpaperFlags);
6974 }
6975 }
6976}
6977
6978sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6979 const sp<WindowInfoHandle>& windowHandle) const {
6980 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6981 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6982 bool foundWindow = false;
6983 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6984 if (!foundWindow && otherHandle != windowHandle) {
6985 continue;
6986 }
6987 if (windowHandle == otherHandle) {
6988 foundWindow = true;
6989 continue;
6990 }
6991
6992 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6993 return otherHandle;
6994 }
6995 }
6996 return nullptr;
6997}
6998
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006999void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
7000 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007001 std::scoped_lock _l(mLock);
7002
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08007003 mConfig.keyRepeatTimeout = timeout.count();
7004 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09007005}
7006
Prabir Pradhan64f21d22023-11-28 21:19:42 +00007007bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
7008 DeviceId deviceId, int32_t pointerId) {
7009 std::scoped_lock _l(mLock);
7010 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7011 if (touchStateIt == mTouchStatesByDisplay.end()) {
7012 return false;
7013 }
7014 for (const TouchedWindow& window : touchStateIt->second.windows) {
7015 if (window.windowHandle->getToken() == token &&
7016 (window.hasTouchingPointer(deviceId, pointerId) ||
7017 window.hasHoveringPointer(deviceId, pointerId))) {
7018 return true;
7019 }
7020 }
7021 return false;
7022}
7023
Garfield Tane84e6f92019-08-29 17:28:41 -07007024} // namespace android::inputdispatcher