blob: efc9b3a26de857ef40b8b0766ead7e14c1f9bd6b [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>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000049#include "../InputDeviceMetricsSource.h"
50
Michael Wright44753b12020-07-08 13:48:11 +010051#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000052#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070053#include "InputDispatcher.h"
Prabir Pradhandae52792023-12-15 07:36:40 +000054#include "trace/InputTracer.h"
55#include "trace/InputTracingPerfettoBackend.h"
Michael Wright44753b12020-07-08 13:48:11 +010056
Michael Wrightd02c5b62014-02-10 15:10:22 -080057#define INDENT " "
58#define INDENT2 " "
59#define INDENT3 " "
60#define INDENT4 " "
61
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080062using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070063using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080064using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000065using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070067using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050068using android::gui::FocusRequest;
69using android::gui::TouchOcclusionMode;
70using android::gui::WindowInfo;
71using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080072using android::os::InputEventInjectionResult;
73using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000074namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075
Garfield Tane84e6f92019-08-29 17:28:41 -070076namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
Prabir Pradhancef936d2021-07-21 16:17:52 +000078namespace {
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000079
Prabir Pradhandae52792023-12-15 07:36:40 +000080// Input tracing is only available on debuggable builds (userdebug and eng) when the feature
81// flag is enabled. When the flag is changed, tracing will only be available after reboot.
82bool isInputTracingEnabled() {
83 static const std::string buildType = base::GetProperty("ro.build.type", "user");
84 static const bool isUserdebugOrEng = buildType == "userdebug" || buildType == "eng";
85 return input_flags::enable_input_event_tracing() && isUserdebugOrEng;
86}
87
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +000088template <class Entry>
89void ensureEventTraced(const Entry& entry) {
90 if (!entry.traceTracker) {
91 LOG(FATAL) << "Expected event entry to be traced, but it wasn't: " << entry;
92 }
93}
94
Prabir Pradhancef936d2021-07-21 16:17:52 +000095// Temporarily releases a held mutex for the lifetime of the instance.
96// Named to match std::scoped_lock
97class scoped_unlock {
98public:
99 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
100 ~scoped_unlock() { mMutex.lock(); }
101
102private:
103 std::mutex& mMutex;
104};
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106// Default input dispatching timeout if there is no focused application or paused window
107// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800108const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
109 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
110 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800112// The default minimum time gap between two user activity poke events.
113const std::chrono::milliseconds DEFAULT_USER_ACTIVITY_POKE_INTERVAL = 100ms;
114
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800115const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117// 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 +0000118constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
119
120// Log a warning when an interception call takes longer than this to process.
121constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700123// Additional key latency in case a connection is still processing some motion events.
124// This will help with the case when a user touched a button that opens a new window,
125// and gives us the chance to dispatch the key to this new window.
126constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000129constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
130
Antonio Kantekea47acb2021-12-23 12:41:25 -0800131// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000132constexpr int LOGTAG_INPUT_INTERACTION = 62000;
133constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000134constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000135
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000136const ui::Transform kIdentityTransform;
137
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000138inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 return systemTime(SYSTEM_TIME_MONOTONIC);
140}
141
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700142inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000143 if (binder == nullptr) {
144 return "<null>";
145 }
146 return StringPrintf("%p", binder.get());
147}
148
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000149static std::string uidString(const gui::Uid& uid) {
150 return uid.toString();
151}
152
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700153Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AKEY_EVENT_ACTION_DOWN:
156 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700157 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700163Result<void> validateKeyEvent(int32_t action) {
164 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165}
166
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700167Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800168 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700170 case AMOTION_EVENT_ACTION_UP: {
171 if (pointerCount != 1) {
172 return Error() << "invalid pointer count " << pointerCount;
173 }
174 return {};
175 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 case AMOTION_EVENT_ACTION_HOVER_ENTER:
178 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
180 if (pointerCount < 1) {
181 return Error() << "invalid pointer count " << pointerCount;
182 }
183 return {};
184 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800185 case AMOTION_EVENT_ACTION_CANCEL:
186 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700188 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 case AMOTION_EVENT_ACTION_POINTER_DOWN:
190 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800191 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700192 if (index < 0) {
193 return Error() << "invalid index " << index << " for "
194 << MotionEvent::actionToString(action);
195 }
196 if (index >= pointerCount) {
197 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
198 }
199 if (pointerCount <= 1) {
200 return Error() << "invalid pointer count " << pointerCount << " for "
201 << MotionEvent::actionToString(action);
202 }
203 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700204 }
205 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700206 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
207 if (actionButton == 0) {
208 return Error() << "action button should be nonzero for "
209 << MotionEvent::actionToString(action);
210 }
211 return {};
212 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700214 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 }
216}
217
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000218int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500219 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
220}
221
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700222Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
223 const PointerProperties* pointerProperties) {
224 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
225 if (!actionCheck.ok()) {
226 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
228 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return Error() << "Motion event has invalid pointer count " << pointerCount
230 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800232 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 for (size_t i = 0; i < pointerCount; i++) {
234 int32_t id = pointerProperties[i].id;
235 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700236 return Error() << "Motion event has invalid pointer id " << id
237 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800239 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700240 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800242 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700244 return {};
245}
246
247Result<void> validateInputEvent(const InputEvent& event) {
248 switch (event.getType()) {
249 case InputEventType::KEY: {
250 const KeyEvent& key = static_cast<const KeyEvent&>(event);
251 const int32_t action = key.getAction();
252 return validateKeyEvent(action);
253 }
254 case InputEventType::MOTION: {
255 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
256 const int32_t action = motion.getAction();
257 const size_t pointerCount = motion.getPointerCount();
258 const PointerProperties* pointerProperties = motion.getPointerProperties();
259 const int32_t actionButton = motion.getActionButton();
260 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
261 }
262 default: {
263 return {};
264 }
265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266}
267
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800268std::bitset<MAX_POINTER_ID + 1> getPointerIds(const std::vector<PointerProperties>& pointers) {
269 std::bitset<MAX_POINTER_ID + 1> pointerIds;
270 for (const PointerProperties& pointer : pointers) {
271 pointerIds.set(pointer.id);
272 }
273 return pointerIds;
274}
275
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000276std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000278 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279 }
280
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000281 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282 bool first = true;
283 Region::const_iterator cur = region.begin();
284 Region::const_iterator const tail = region.end();
285 while (cur != tail) {
286 if (first) {
287 first = false;
288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800289 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800291 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292 cur++;
293 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000294 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295}
296
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000297std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
298 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500299 constexpr size_t maxEntries = 50; // max events to print
300 constexpr size_t skipBegin = maxEntries / 2;
301 const size_t skipEnd = queue.size() - maxEntries / 2;
302 // skip from maxEntries / 2 ... size() - maxEntries/2
303 // only print from 0 .. skipBegin and then from skipEnd .. size()
304
305 std::string dump;
306 for (size_t i = 0; i < queue.size(); i++) {
307 const DispatchEntry& entry = *queue[i];
308 if (i >= skipBegin && i < skipEnd) {
309 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
310 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
311 continue;
312 }
313 dump.append(INDENT4);
314 dump += entry.eventEntry->getDescription();
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +0000315 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, age=%" PRId64 "ms", entry.seq,
316 entry.targetFlags.string().c_str(),
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500317 ns2ms(currentTime - entry.eventEntry->eventTime));
318 if (entry.deliveryTime != 0) {
319 // This entry was delivered, so add information on how long we've been waiting
320 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
321 }
322 dump.append("\n");
323 }
324 return dump;
325}
326
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700327/**
328 * Find the entry in std::unordered_map by key, and return it.
329 * If the entry is not found, return a default constructed entry.
330 *
331 * Useful when the entries are vectors, since an empty vector will be returned
332 * if the entry is not found.
333 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
334 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700335template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000336V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700337 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700338 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800339}
340
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000341bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700342 if (first == second) {
343 return true;
344 }
345
346 if (first == nullptr || second == nullptr) {
347 return false;
348 }
349
350 return first->getToken() == second->getToken();
351}
352
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000353bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000354 if (first == nullptr || second == nullptr) {
355 return false;
356 }
357 return first->applicationInfo.token != nullptr &&
358 first->applicationInfo.token == second->applicationInfo.token;
359}
360
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800361template <typename T>
362size_t firstMarkedBit(T set) {
363 // TODO: replace with std::countr_zero from <bit> when that's available
364 LOG_ALWAYS_FATAL_IF(set.none());
365 size_t i = 0;
366 while (!set.test(i)) {
367 i++;
368 }
369 return i;
370}
371
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800372std::unique_ptr<DispatchEntry> createDispatchEntry(
Prabir Pradhan24047542023-11-02 17:14:59 +0000373 const InputTarget& inputTarget, std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800374 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 if (inputTarget.useDefaultPointerTransform()) {
376 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700378 inputTarget.displayTransform,
379 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380 }
381
382 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
383 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
384
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700385 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700386 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387
388 // Use the first pointer information to normalize all other pointers. This could be any pointer
389 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700390 // uses the transform for the normalized pointer.
391 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800392 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700393 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000394
395 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700396 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000397 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
398 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700399 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700402 // First, apply the current pointer's transform to update the coordinates into
403 // window space.
404 pointerCoords[pointerIndex].transform(currTransform);
405 // Next, apply the inverse transform of the normalized coordinates so the
406 // current coordinates are transformed into the normalized coordinate space.
407 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000408 }
409
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700410 std::unique_ptr<MotionEntry> combinedMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +0000411 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.injectionState,
412 motionEntry.eventTime, motionEntry.deviceId,
413 motionEntry.source, motionEntry.displayId,
414 motionEntry.policyFlags, motionEntry.action,
415 motionEntry.actionButton, motionEntry.flags,
416 motionEntry.metaState, motionEntry.buttonState,
417 motionEntry.classification, motionEntry.edgeFlags,
418 motionEntry.xPrecision, motionEntry.yPrecision,
419 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
420 motionEntry.downTime, motionEntry.pointerProperties,
421 pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000422
423 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700424 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700425 firstPointerTransform, inputTarget.displayTransform,
426 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000427 return dispatchEntry;
428}
429
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000430status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
431 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700432 std::unique_ptr<InputChannel> uniqueServerChannel;
433 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
434
435 serverChannel = std::move(uniqueServerChannel);
436 return result;
437}
438
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500439template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000440bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500441 if (lhs == nullptr && rhs == nullptr) {
442 return true;
443 }
444 if (lhs == nullptr || rhs == nullptr) {
445 return false;
446 }
447 return *lhs == *rhs;
448}
449
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000450KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000451 KeyEvent event;
452 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
453 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
454 entry.repeatCount, entry.downTime, entry.eventTime);
455 return event;
456}
457
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000458bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000459 // Do not keep track of gesture monitors. They receive every event and would disproportionately
460 // affect the statistics.
461 if (connection.monitor) {
462 return false;
463 }
464 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
465 if (!connection.responsive) {
466 return false;
467 }
468 return true;
469}
470
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000471bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000472 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
473 const int32_t& inputEventId = eventEntry.id;
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000474 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
475 return false;
476 }
477 // Only track latency for events that originated from hardware
478 if (eventEntry.isSynthesized()) {
479 return false;
480 }
481 const EventEntry::Type& inputEventEntryType = eventEntry.type;
482 if (inputEventEntryType == EventEntry::Type::KEY) {
483 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
484 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
485 return false;
486 }
487 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
488 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
489 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
490 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
491 return false;
492 }
493 } else {
494 // Not a key or a motion
495 return false;
496 }
497 if (!shouldReportMetricsForConnection(connection)) {
498 return false;
499 }
500 return true;
501}
502
Prabir Pradhancef936d2021-07-21 16:17:52 +0000503/**
504 * Connection is responsive if it has no events in the waitQueue that are older than the
505 * current time.
506 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000507bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000508 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000509 for (const auto& dispatchEntry : connection.waitQueue) {
510 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000511 return false;
512 }
513 }
514 return true;
515}
516
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517// Returns true if the event type passed as argument represents a user activity.
518bool isUserActivityEvent(const EventEntry& eventEntry) {
519 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000520 case EventEntry::Type::CONFIGURATION_CHANGED:
521 case EventEntry::Type::DEVICE_RESET:
522 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000523 case EventEntry::Type::FOCUS:
524 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000525 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000526 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000527 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000528 case EventEntry::Type::KEY:
529 case EventEntry::Type::MOTION:
530 return true;
531 }
532}
533
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000535bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800537 const auto inputConfig = windowInfo.inputConfig;
538 if (windowInfo.displayId != displayId ||
539 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800540 return false;
541 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700542 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800543 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800544 return false;
545 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000546
547 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
548 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
549 // the window. Points on the right and bottom edges should not be inside the window, so we need
550 // to be careful about performing a hit test when the display is rotated, since the "right" and
551 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
552 // logical display in which WM determined the bounds. Perform the hit test in the logical
553 // display space to ensure these edges are considered correctly in all orientations.
554 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
555 const auto p = displayTransform.transform(x, y);
556 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800557 return false;
558 }
559 return true;
560}
561
Prabir Pradhand65552b2021-10-07 11:23:50 -0700562bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
563 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000564 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700565}
566
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800567// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000568// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
569// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
570// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800571// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000572bool canReceiveForegroundTouches(const WindowInfo& info) {
573 // A non-touchable window can still receive touch events (e.g. in the case of
574 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
575 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
576}
577
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000578bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700579 if (windowHandle == nullptr) {
580 return false;
581 }
582 const WindowInfo* windowInfo = windowHandle->getInfo();
583 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
584 return true;
585 }
586 return false;
587}
588
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589// Checks targeted injection using the window's owner's uid.
590// Returns an empty string if an entry can be sent to the given window, or an error message if the
591// entry is a targeted injection whose uid target doesn't match the window owner.
592std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
593 const EventEntry& entry) {
594 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
595 // The event was not injected, or the injected event does not target a window.
596 return {};
597 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000598 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000599 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000600 return StringPrintf("No valid window target for injection into uid %s.",
601 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000602 }
603 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000604 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
605 "owned by uid %s.",
606 uid.toString().c_str(), window->getName().c_str(),
607 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000608 }
609 return {};
610}
611
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000612std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700613 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
614 // Always dispatch mouse events to cursor position.
615 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000616 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700617 }
618
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700619 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000620 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
621 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700622}
623
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700624std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
625 if (eventEntry.type == EventEntry::Type::KEY) {
626 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
627 return keyEntry.downTime;
628 } else if (eventEntry.type == EventEntry::Type::MOTION) {
629 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
630 return motionEntry.downTime;
631 }
632 return std::nullopt;
633}
634
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000635/**
636 * Compare the old touch state to the new touch state, and generate the corresponding touched
637 * windows (== input targets).
638 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
639 * If the pointer just entered the new window, produce HOVER_ENTER.
640 * For pointers remaining in the window, produce HOVER_MOVE.
641 */
642std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
643 const TouchState& newTouchState,
644 const MotionEntry& entry) {
645 std::vector<TouchedWindow> out;
646 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -0700647
648 if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
649 // ACTION_SCROLL events should not affect the hovering pointer dispatch
650 return {};
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000651 }
652
653 // We should consider all hovering pointers here. But for now, just use the first one
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800654 const PointerProperties& pointer = entry.pointerProperties[0];
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000655
656 std::set<sp<WindowInfoHandle>> oldWindows;
657 if (oldState != nullptr) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800658 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000659 }
660
661 std::set<sp<WindowInfoHandle>> newWindows =
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800662 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointer.id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000663
664 // If the pointer is no longer in the new window set, send HOVER_EXIT.
665 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
666 if (newWindows.find(oldWindow) == newWindows.end()) {
667 TouchedWindow touchedWindow;
668 touchedWindow.windowHandle = oldWindow;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000669 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000670 out.push_back(touchedWindow);
671 }
672 }
673
674 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
675 TouchedWindow touchedWindow;
676 touchedWindow.windowHandle = newWindow;
677 if (oldWindows.find(newWindow) == oldWindows.end()) {
678 // Any windows that have this pointer now, and didn't have it before, should get
679 // HOVER_ENTER
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000680 touchedWindow.dispatchMode = InputTarget::DispatchMode::HOVER_ENTER;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000681 } else {
682 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700684 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000685 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
686 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700687 // The Accessibility injected touch exploration event stream
688 // has known inconsistencies, so log ERROR instead of
689 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700690 severity = android::base::LogSeverity::ERROR;
691 }
692 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700693 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +0000694 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000695 }
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -0800696 touchedWindow.addHoveringPointer(entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000697 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
698 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
699 }
700 out.push_back(touchedWindow);
701 }
702 return out;
703}
704
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800705template <typename T>
706std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
707 left.insert(left.end(), right.begin(), right.end());
708 return left;
709}
710
Harry Cuttsb166c002023-05-09 13:06:05 +0000711// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
712// both.
713void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
714 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
715 if (!window.windowHandle->getInfo()->inputConfig.test(
716 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
717 // In addition to TouchState, erase this window from the input targets! We don't have a
718 // good way to do this today except by adding a nested loop.
719 // TODO(b/282025641): simplify this code once InputTargets are being identified
720 // separately from TouchedWindows.
721 std::erase_if(targets, [&](const InputTarget& target) {
722 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
723 });
724 return true;
725 }
726 return false;
727 });
728}
729
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700730/**
731 * In general, touch should be always split between windows. Some exceptions:
732 * 1. Don't split touch if all of the below is true:
733 * (a) we have an active pointer down *and*
734 * (b) a new pointer is going down that's from the same device *and*
735 * (c) the window that's receiving the current pointer does not support split touch.
736 * 2. Don't split mouse events
737 */
738bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
739 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
740 // We should never split mouse events
741 return false;
742 }
743 for (const TouchedWindow& touchedWindow : touchState.windows) {
744 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
745 // Spy windows should not affect whether or not touch is split.
746 continue;
747 }
748 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
749 continue;
750 }
751 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
752 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
753 // Wallpaper window should not affect whether or not touch is split
754 continue;
755 }
756
757 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
758 return false;
759 }
760 }
761 return true;
762}
763
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -0700764/**
765 * Return true if stylus is currently down anywhere on the specified display, and false otherwise.
766 */
767bool isStylusActiveInDisplay(
768 int32_t displayId,
769 const std::unordered_map<int32_t /*displayId*/, TouchState>& touchStatesByDisplay) {
770 const auto it = touchStatesByDisplay.find(displayId);
771 if (it == touchStatesByDisplay.end()) {
772 return false;
773 }
774 const TouchState& state = it->second;
775 return state.hasActiveStylus();
776}
777
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -0800778Result<void> validateWindowInfosUpdate(const gui::WindowInfosUpdate& update) {
779 struct HashFunction {
780 size_t operator()(const WindowInfo& info) const { return info.id; }
781 };
782
783 std::unordered_set<WindowInfo, HashFunction> windowSet;
784 for (const WindowInfo& info : update.windowInfos) {
785 const auto [_, inserted] = windowSet.insert(info);
786 if (!inserted) {
787 return Error() << "Duplicate entry for " << info;
788 }
789 }
790 return {};
791}
792
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800793int32_t getUserActivityEventType(const EventEntry& eventEntry) {
794 switch (eventEntry.type) {
795 case EventEntry::Type::KEY: {
796 return USER_ACTIVITY_EVENT_BUTTON;
797 }
798 case EventEntry::Type::MOTION: {
799 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
800 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
801 return USER_ACTIVITY_EVENT_TOUCH;
802 }
803 return USER_ACTIVITY_EVENT_OTHER;
804 }
805 default: {
806 LOG_ALWAYS_FATAL("%s events are not user activity",
807 ftl::enum_string(eventEntry.type).c_str());
808 }
809 }
810}
811
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000812} // namespace
813
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814// --- InputDispatcher ---
815
Prabir Pradhana41d2442023-04-20 21:30:40 +0000816InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Prabir Pradhandae52792023-12-15 07:36:40 +0000817 : InputDispatcher(policy,
818 isInputTracingEnabled() ? std::make_unique<trace::impl::PerfettoBackend>()
819 : nullptr) {}
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000820
821InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
822 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
Garfield Tan00f511d2019-06-12 16:55:40 -0700823 : mPolicy(policy),
824 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700825 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800826 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800827 mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
Garfield Tan00f511d2019-06-12 16:55:40 -0700828 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800829 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700830 mDispatchEnabled(false),
831 mDispatchFrozen(false),
832 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100833 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000834 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800835 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000836 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000837 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700838 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800839 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700841 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700842#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700843 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700844#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700845 mKeyRepeatState.lastKeyEntry = nullptr;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000846
847 if (traceBackend) {
Prabir Pradhandae52792023-12-15 07:36:40 +0000848 mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +0000849 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -0800850
851 mLastUserActivityTimes.fill(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852}
853
854InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000855 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
Prabir Pradhancef936d2021-07-21 16:17:52 +0000857 resetKeyRepeatLocked();
858 releasePendingEventLocked();
859 drainInboundQueueLocked();
860 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000862 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700863 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000864 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866}
867
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700868status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700869 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700870 return ALREADY_EXISTS;
871 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700872 mThread = std::make_unique<InputThread>(
873 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
874 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700875}
876
877status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700878 if (mThread && mThread->isCallingThread()) {
879 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700880 return INVALID_OPERATION;
881 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700882 mThread.reset();
883 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700884}
885
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700887 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800889 std::scoped_lock _l(mLock);
890 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891
892 // Run a dispatch loop if there are no pending commands.
893 // The dispatch loop might enqueue commands to run afterwards.
894 if (!haveCommandsLocked()) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -0800895 dispatchOnceInnerLocked(/*byref*/ nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897
898 // Run all pending commands if there are any.
899 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000900 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700901 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800903
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700904 // If we are still waiting for ack on some events,
905 // we might have to wake up earlier to check if an app is anr'ing.
906 const nsecs_t nextAnrCheck = processAnrsLocked();
907 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
908
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800909 // We are about to enter an infinitely long sleep, because we have no commands or
910 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700911 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800912 mDispatcherEnteredIdle.notify_all();
913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 } // release lock
915
916 // Wait for callback or timeout or wake. (make sure we round up, not down)
917 nsecs_t currentTime = now();
918 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
919 mLooper->pollOnce(timeoutMillis);
920}
921
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700922/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500923 * Raise ANR if there is no focused window.
924 * Before the ANR is raised, do a final state check:
925 * 1. The currently focused application must be the same one we are waiting for.
926 * 2. Ensure we still don't have a focused window.
927 */
928void InputDispatcher::processNoFocusedWindowAnrLocked() {
929 // Check if the application that we are waiting for is still focused.
930 std::shared_ptr<InputApplicationHandle> focusedApplication =
931 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
932 if (focusedApplication == nullptr ||
933 focusedApplication->getApplicationToken() !=
934 mAwaitedFocusedApplication->getApplicationToken()) {
935 // Unexpected because we should have reset the ANR timer when focused application changed
936 ALOGE("Waited for a focused window, but focused application has already changed to %s",
937 focusedApplication->getName().c_str());
938 return; // The focused application has changed.
939 }
940
chaviw98318de2021-05-19 16:45:23 -0500941 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500942 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
943 if (focusedWindowHandle != nullptr) {
944 return; // We now have a focused window. No need for ANR.
945 }
946 onAnrLocked(mAwaitedFocusedApplication);
947}
948
949/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 * Check if any of the connections' wait queues have events that are too old.
951 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
952 * Return the time at which we should wake up next.
953 */
954nsecs_t InputDispatcher::processAnrsLocked() {
955 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700956 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
958 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
959 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500960 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700961 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500962 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700963 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700964 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500965 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
967 }
968 }
969
970 // Check if any connection ANRs are due
971 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
972 if (currentTime < nextAnrCheck) { // most likely scenario
973 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
974 }
975
976 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700977 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700978 if (connection == nullptr) {
979 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
980 return nextAnrCheck;
981 }
982 connection->responsive = false;
983 // Stop waking up for this unresponsive connection
984 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000985 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700986 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700987}
988
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800989std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700990 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800991 if (connection->monitor) {
992 return mMonitorDispatchingTimeout;
993 }
994 const sp<WindowInfoHandle> window =
995 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500997 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700998 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500999 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001000}
1001
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001002void InputDispatcher::dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 nsecs_t currentTime = now();
1004
Jeff Browndc5992e2014-04-11 01:27:26 -07001005 // Reset the key repeat timer whenever normal dispatch is suspended while the
1006 // device is in a non-interactive state. This is to ensure that we abort a key
1007 // repeat if the device is just coming out of sleep.
1008 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 resetKeyRepeatLocked();
1010 }
1011
1012 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
1013 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001014 if (DEBUG_FOCUS) {
1015 ALOGD("Dispatch frozen. Waiting some more.");
1016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 return;
1018 }
1019
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 // Ready to start a new event.
1021 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001023 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 // Synthesize a key repeat if appropriate.
1025 if (mKeyRepeatState.lastKeyEntry) {
1026 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
1027 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
1028 } else {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001029 nextWakeupTime = std::min(nextWakeupTime, mKeyRepeatState.nextRepeatTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
1031 }
1032
1033 // Nothing to do if there is no pending event.
1034 if (!mPendingEvent) {
1035 return;
1036 }
1037 } else {
1038 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001039 mPendingEvent = mInboundQueue.front();
1040 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 traceInboundQueueLengthLocked();
1042 }
1043
1044 // Poke user activity for this event.
1045 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001046 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
1049
1050 // Now we have an event to dispatch.
1051 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001052 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001054 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001056 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060
1061 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001062 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 }
1064
1065 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067 const ConfigurationChangedEntry& typedEntry =
1068 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001070 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 break;
1072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001074 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075 const DeviceResetEntry& typedEntry =
1076 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 break;
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001082 case EventEntry::Type::FOCUS: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001083 std::shared_ptr<const FocusEntry> typedEntry =
1084 std::static_pointer_cast<const FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085 dispatchFocusLocked(currentTime, typedEntry);
1086 done = true;
1087 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1088 break;
1089 }
1090
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001091 case EventEntry::Type::TOUCH_MODE_CHANGED: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001092 const auto typedEntry = std::static_pointer_cast<const TouchModeEntry>(mPendingEvent);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001093 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1094 done = true;
1095 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1096 break;
1097 }
1098
Prabir Pradhan99987712020-11-10 18:43:05 -08001099 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1100 const auto typedEntry =
Prabir Pradhan24047542023-11-02 17:14:59 +00001101 std::static_pointer_cast<const PointerCaptureChangedEntry>(mPendingEvent);
Prabir Pradhan99987712020-11-10 18:43:05 -08001102 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1103 done = true;
1104 break;
1105 }
1106
arthurhungb89ccb02020-12-30 16:19:01 +08001107 case EventEntry::Type::DRAG: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001108 std::shared_ptr<const DragEntry> typedEntry =
1109 std::static_pointer_cast<const DragEntry>(mPendingEvent);
arthurhungb89ccb02020-12-30 16:19:01 +08001110 dispatchDragLocked(currentTime, typedEntry);
1111 done = true;
1112 break;
1113 }
1114
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001115 case EventEntry::Type::KEY: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001116 std::shared_ptr<const KeyEntry> keyEntry =
1117 std::static_pointer_cast<const KeyEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001118 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1122 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001124 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001125 if (done && mTracer) {
1126 ensureEventTraced(*keyEntry);
1127 mTracer->eventProcessingComplete(*keyEntry->traceTracker);
1128 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 break;
1130 }
1131
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::MOTION: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001133 std::shared_ptr<const MotionEntry> motionEntry =
1134 std::static_pointer_cast<const MotionEntry>(mPendingEvent);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001135 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou6b71b632023-10-27 21:34:46 -07001136 // The event is stale. However, only drop stale events if there isn't an ongoing
1137 // gesture. That would allow us to complete the processing of the current stroke.
1138 const auto touchStateIt = mTouchStatesByDisplay.find(motionEntry->displayId);
1139 if (touchStateIt != mTouchStatesByDisplay.end()) {
1140 const TouchState& touchState = touchStateIt->second;
1141 if (!touchState.hasTouchingPointers(motionEntry->deviceId) &&
1142 !touchState.hasHoveringPointers(motionEntry->deviceId)) {
1143 dropReason = DropReason::STALE;
1144 }
1145 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001147 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001148 if (!isFromSource(motionEntry->source, AINPUT_SOURCE_CLASS_POINTER)) {
1149 // Only drop events that are focus-dispatched.
1150 dropReason = DropReason::BLOCKED;
1151 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001153 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001154 if (done && mTracer) {
1155 ensureEventTraced(*motionEntry);
1156 mTracer->eventProcessingComplete(*motionEntry->traceTracker);
1157 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 }
Chris Yef59a2f42020-10-16 12:55:26 -07001160
1161 case EventEntry::Type::SENSOR: {
Prabir Pradhan24047542023-11-02 17:14:59 +00001162 std::shared_ptr<const SensorEntry> sensorEntry =
1163 std::static_pointer_cast<const SensorEntry>(mPendingEvent);
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001164
Chris Yef59a2f42020-10-16 12:55:26 -07001165 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1166 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1167 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1168 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1169 dropReason = DropReason::STALE;
1170 }
1171 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1172 done = true;
1173 break;
1174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
1176
1177 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001178 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001179 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 }
Michael Wright3a981722015-06-10 15:26:13 +01001181 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182
1183 releasePendingEventLocked();
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001184 nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186}
1187
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001188bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakoua7333112023-10-27 13:33:29 -07001189 return mPolicy.isStaleEvent(currentTime, entry.eventTime);
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001190}
1191
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001192/**
1193 * Return true if the events preceding this incoming motion event should be dropped
1194 * Return false otherwise (the default behaviour)
1195 */
1196bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001197 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001198 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001199
1200 // Optimize case where the current application is unresponsive and the user
1201 // decides to touch a window in a different application.
1202 // If the application takes too long to catch up then we drop all events preceding
1203 // the touch into the other window.
1204 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001205 const int32_t displayId = motionEntry.displayId;
1206 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001207 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001208
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001209 sp<WindowInfoHandle> touchedWindowHandle =
1210 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001211 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001212 touchedWindowHandle->getApplicationToken() !=
1213 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001215 ALOGI("Pruning input queue because user touched a different application while waiting "
1216 "for %s",
1217 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218 return true;
1219 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001221 // Alternatively, maybe there's a spy window that could handle this event.
1222 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1223 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1224 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001225 const std::shared_ptr<Connection> connection =
1226 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001227 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001228 // This spy window could take more input. Drop all events preceding this
1229 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001230 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001231 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001232 mAwaitedFocusedApplication->getName().c_str());
1233 return true;
1234 }
1235 }
1236 }
1237
1238 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1239 // yet been processed by some connections, the dispatcher will wait for these motion
1240 // events to be processed before dispatching the key event. This is because these motion events
1241 // may cause a new window to be launched, which the user might expect to receive focus.
1242 // To prevent waiting forever for such events, just send the key to the currently focused window
1243 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1244 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1245 "just send the pending key event to the focused window.");
1246 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 }
1248 return false;
1249}
1250
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001252 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 mInboundQueue.push_back(std::move(newEntry));
Prabir Pradhan24047542023-11-02 17:14:59 +00001254 const EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 traceInboundQueueLengthLocked();
1256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001258 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001259 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1260 "Unexpected untrusted event.");
Siarhei Vishniakoue2404a12024-01-16 18:38:39 -08001261
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001263 if (mTracer) {
1264 ensureEventTraced(keyEntry);
1265 }
Siarhei Vishniakou6520a582023-10-27 21:53:45 -07001266
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001267 // If a new up event comes in, and the pending event with same key code has been asked
1268 // to try again later because of the policy. We have to reset the intercept key wake up
1269 // time for it may have been handled in the policy and could be dropped.
1270 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1271 mPendingEvent->type == EventEntry::Type::KEY) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001272 const KeyEntry& pendingKey = static_cast<const KeyEntry&>(*mPendingEvent);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001273 if (pendingKey.keyCode == keyEntry.keyCode &&
1274 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001275 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1276 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001277 pendingKey.interceptKeyWakeupTime = 0;
1278 needWake = true;
1279 }
1280 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 break;
1282 }
1283
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001284 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001285 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1286 "Unexpected untrusted event.");
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001287 const auto& motionEntry = static_cast<const MotionEntry&>(entry);
1288 if (mTracer) {
1289 ensureEventTraced(motionEntry);
1290 }
1291 if (shouldPruneInboundQueueLocked(motionEntry)) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001293 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001297 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001298 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1299 break;
1300 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001301 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001303 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001304 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001305 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1306 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001307 // nothing to do
1308 break;
1309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311
1312 return needWake;
1313}
1314
Prabir Pradhan24047542023-11-02 17:14:59 +00001315void InputDispatcher::addRecentEventLocked(std::shared_ptr<const EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001316 // Do not store sensor event in recent queue to avoid flooding the queue.
1317 if (entry->type != EventEntry::Type::SENSOR) {
1318 mRecentQueue.push_back(entry);
1319 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001320 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323}
1324
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001325sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1326 bool isStylus,
1327 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001329 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001330 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001331 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001332 continue;
1333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001335 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001336 if (!info.isSpy() &&
1337 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001338 return windowHandle;
1339 }
1340 }
1341 return nullptr;
1342}
1343
1344std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001345 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001346 if (touchedWindow == nullptr) {
1347 return {};
1348 }
1349 // Traverse windows from front to back until we encounter the touched window.
1350 std::vector<InputTarget> outsideTargets;
1351 const auto& windowHandles = getWindowHandlesLocked(displayId);
1352 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1353 if (windowHandle == touchedWindow) {
1354 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1355 // below the touched window will not get ACTION_OUTSIDE event.
1356 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001357 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001358
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001359 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001360 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001361 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1362 pointerIds.set(pointerId);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001363 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::OUTSIDE,
1364 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001365 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001368 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369}
1370
Prabir Pradhand65552b2021-10-07 11:23:50 -07001371std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001372 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001373 // Traverse windows from front to back and gather the touched spy windows.
1374 std::vector<sp<WindowInfoHandle>> spyWindows;
1375 const auto& windowHandles = getWindowHandlesLocked(displayId);
1376 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1377 const WindowInfo& info = *windowHandle->getInfo();
1378
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001379 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001380 continue;
1381 }
1382 if (!info.isSpy()) {
1383 // The first touched non-spy window was found, so return the spy windows touched so far.
1384 return spyWindows;
1385 }
1386 spyWindows.push_back(windowHandle);
1387 }
1388 return spyWindows;
1389}
1390
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 const char* reason;
1393 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001394 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001395 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001396 ALOGD("Dropped event because policy consumed it.");
1397 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 reason = "inbound event was dropped because the policy consumed it";
1399 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001400 case DropReason::DISABLED:
1401 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 ALOGI("Dropped event because input dispatch is disabled.");
1403 }
1404 reason = "inbound event was dropped because input dispatch is disabled";
1405 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001406 case DropReason::BLOCKED:
Siarhei Vishniakou99e407b2023-12-26 18:09:32 -08001407 LOG(INFO) << "Dropping because the current application is not responding and the user "
1408 "has started interacting with a different application: "
1409 << entry.getDescription();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 reason = "inbound event was dropped because the current application is not responding "
1411 "and the user has started interacting with a different application";
1412 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001413 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 ALOGI("Dropped event because it is stale.");
1415 reason = "inbound event was dropped because it is stale";
1416 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001417 case DropReason::NO_POINTER_CAPTURE:
1418 ALOGI("Dropped event because there is no window with Pointer Capture.");
1419 reason = "inbound event was dropped because there is no window with Pointer Capture";
1420 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001421 case DropReason::NOT_DROPPED: {
1422 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 }
1426
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001427 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001428 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001429 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001430 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1431 options.displayId = keyEntry.displayId;
1432 options.deviceId = keyEntry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001436 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001437 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1438 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001439 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001440 options.displayId = motionEntry.displayId;
1441 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001442 synthesizeCancelationEventsForAllConnectionsLocked(options);
1443 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001444 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1445 reason);
Hu Guo3cfa7382023-11-15 09:50:04 +00001446 options.displayId = motionEntry.displayId;
1447 options.deviceId = motionEntry.deviceId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001448 synthesizeCancelationEventsForAllConnectionsLocked(options);
1449 }
1450 break;
1451 }
Chris Yef59a2f42020-10-16 12:55:26 -07001452 case EventEntry::Type::SENSOR: {
1453 break;
1454 }
arthurhungb89ccb02020-12-30 16:19:01 +08001455 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1456 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001457 break;
1458 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001459 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001460 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001461 case EventEntry::Type::CONFIGURATION_CHANGED:
1462 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001463 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001464 break;
1465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467}
1468
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001470 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471}
1472
Prabir Pradhancef936d2021-07-21 16:17:52 +00001473bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001474 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return false;
1476 }
1477
1478 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001479 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001480 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001481 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1482 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001483 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 return true;
1485}
1486
Prabir Pradhancef936d2021-07-21 16:17:52 +00001487void InputDispatcher::postCommandLocked(Command&& command) {
1488 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489}
1490
1491void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001492 while (!mInboundQueue.empty()) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001493 std::shared_ptr<const EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001494 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 releaseInboundEventLocked(entry);
1496 }
1497 traceInboundQueueLengthLocked();
1498}
1499
1500void InputDispatcher::releasePendingEventLocked() {
1501 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001503 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 }
1505}
1506
Prabir Pradhan24047542023-11-02 17:14:59 +00001507void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<const EventEntry> entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001508 const std::shared_ptr<InjectionState>& injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001509 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001510 if (DEBUG_DISPATCH_CYCLE) {
1511 ALOGD("Injected inbound event was dropped.");
1512 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001516 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
1521void InputDispatcher::resetKeyRepeatLocked() {
1522 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001523 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 }
1525}
1526
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001528 std::shared_ptr<const KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529
Michael Wright2e732952014-09-24 13:26:59 -07001530 uint32_t policyFlags = entry->policyFlags &
1531 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001533 std::shared_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00001534 std::make_unique<KeyEntry>(mIdGenerator.nextId(), /*injectionState=*/nullptr,
1535 currentTime, entry->deviceId, entry->source,
1536 entry->displayId, policyFlags, entry->action, entry->flags,
1537 entry->keyCode, entry->scanCode, entry->metaState,
1538 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001540 newEntry->syntheticRepeat = true;
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001541 if (mTracer) {
1542 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
1543 }
1544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001545 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001547 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548}
1549
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001551 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001552 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1553 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555
1556 // Reset key repeating in case a keyboard device was added or removed or something.
1557 resetKeyRepeatLocked();
1558
1559 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001560 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1561 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001562 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001563 };
1564 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return true;
1566}
1567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1569 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001570 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1571 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1572 entry.deviceId);
1573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574
liushenxiang42232912021-05-21 20:24:09 +08001575 // Reset key repeating in case a keyboard device was disabled or enabled.
1576 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1577 resetKeyRepeatLocked();
1578 }
1579
Michael Wrightfb04fd52022-11-24 22:31:11 +00001580 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001583
1584 // Remove all active pointers from this device
1585 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1586 touchState.removeAllPointersForDevice(entry.deviceId);
1587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 return true;
1589}
1590
Vishnu Nairad321cd2020-08-20 16:40:21 -07001591void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001592 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001593 if (mPendingEvent != nullptr) {
1594 // Move the pending event to the front of the queue. This will give the chance
1595 // for the pending event to get dispatched to the newly focused window
1596 mInboundQueue.push_front(mPendingEvent);
1597 mPendingEvent = nullptr;
1598 }
1599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600 std::unique_ptr<FocusEntry> focusEntry =
1601 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1602 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001603
1604 // This event should go to the front of the queue, but behind all other focus events
1605 // Find the last focus event, and insert right after it
Prabir Pradhan24047542023-11-02 17:14:59 +00001606 auto it = std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1607 [](const std::shared_ptr<const EventEntry>& event) {
1608 return event->type == EventEntry::Type::FOCUS;
1609 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001610
1611 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001612 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001613}
1614
Prabir Pradhan24047542023-11-02 17:14:59 +00001615void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime,
1616 std::shared_ptr<const FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001617 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001618 if (channel == nullptr) {
1619 return; // Window has gone away
1620 }
1621 InputTarget target;
1622 target.inputChannel = channel;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001623 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001624 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1625 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001626 std::string reason = std::string("reason=").append(entry->reason);
1627 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001628 dispatchEventLocked(currentTime, entry, {target});
1629}
1630
Prabir Pradhan99987712020-11-10 18:43:05 -08001631void InputDispatcher::dispatchPointerCaptureChangedLocked(
Prabir Pradhan24047542023-11-02 17:14:59 +00001632 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry,
Prabir Pradhan99987712020-11-10 18:43:05 -08001633 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001634 dropReason = DropReason::NOT_DROPPED;
1635
Prabir Pradhan99987712020-11-10 18:43:05 -08001636 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001637 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001638
1639 if (entry->pointerCaptureRequest.enable) {
1640 // Enable Pointer Capture.
1641 if (haveWindowWithPointerCapture &&
1642 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001643 // This can happen if pointer capture is disabled and re-enabled before we notify the
1644 // app of the state change, so there is no need to notify the app.
1645 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1646 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001647 }
1648 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001649 // This can happen if a window requests capture and immediately releases capture.
1650 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001651 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001652 return;
1653 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001654 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1655 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1656 return;
1657 }
1658
Vishnu Nairc519ff72021-01-21 08:23:08 -08001659 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001660 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1661 mWindowTokenWithPointerCapture = token;
1662 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001663 // Disable Pointer Capture.
1664 // We do not check if the sequence number matches for requests to disable Pointer Capture
1665 // for two reasons:
1666 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1667 // to disable capture with the same sequence number: one generated by
1668 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1669 // Capture being disabled in InputReader.
1670 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1671 // actual Pointer Capture state that affects events being generated by input devices is
1672 // in InputReader.
1673 if (!haveWindowWithPointerCapture) {
1674 // Pointer capture was already forcefully disabled because of focus change.
1675 dropReason = DropReason::NOT_DROPPED;
1676 return;
1677 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001678 token = mWindowTokenWithPointerCapture;
1679 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001680 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001681 setPointerCaptureLocked(false);
1682 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001683 }
1684
1685 auto channel = getInputChannelLocked(token);
1686 if (channel == nullptr) {
1687 // Window has gone away, clean up Pointer Capture state.
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 return;
1693 }
1694 InputTarget target;
1695 target.inputChannel = channel;
Prabir Pradhan99987712020-11-10 18:43:05 -08001696 entry->dispatchInProgress = true;
1697 dispatchEventLocked(currentTime, entry, {target});
1698
1699 dropReason = DropReason::NOT_DROPPED;
1700}
1701
Prabir Pradhan24047542023-11-02 17:14:59 +00001702void InputDispatcher::dispatchTouchModeChangeLocked(
1703 nsecs_t currentTime, const std::shared_ptr<const TouchModeEntry>& entry) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001704 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001705 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001706 if (windowHandles.empty()) {
1707 return;
1708 }
1709 const std::vector<InputTarget> inputTargets =
1710 getInputTargetsFromWindowHandlesLocked(windowHandles);
1711 if (inputTargets.empty()) {
1712 return;
1713 }
1714 entry->dispatchInProgress = true;
1715 dispatchEventLocked(currentTime, entry, inputTargets);
1716}
1717
1718std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1719 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1720 std::vector<InputTarget> inputTargets;
1721 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001722 const sp<IBinder>& token = handle->getToken();
1723 if (token == nullptr) {
1724 continue;
1725 }
1726 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1727 if (channel == nullptr) {
1728 continue; // Window has gone away
1729 }
1730 InputTarget target;
1731 target.inputChannel = channel;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001732 inputTargets.push_back(target);
1733 }
1734 return inputTargets;
1735}
1736
Prabir Pradhan24047542023-11-02 17:14:59 +00001737bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001738 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 if (!entry->dispatchInProgress) {
1741 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1742 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1743 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1744 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001745 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 // We have seen two identical key downs in a row which indicates that the device
1747 // driver is automatically generating key repeats itself. We take note of the
1748 // repeat here, but we disable our own next key repeat timer since it is clear that
1749 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001750 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1751 // Make sure we don't get key down from a different device. If a different
1752 // device Id has same key pressed down, the new device Id will replace the
1753 // current one to hold the key repeat with repeat count reset.
1754 // In the future when got a KEY_UP on the device id, drop it and do not
1755 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1757 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001758 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 } else {
1760 // Not a repeat. Save key down state in case we do see a repeat later.
1761 resetKeyRepeatLocked();
1762 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1763 }
1764 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001765 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1766 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001767 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001768 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001769 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1770 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 resetKeyRepeatLocked();
1773 }
1774
1775 if (entry->repeatCount == 1) {
1776 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1777 } else {
1778 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1779 }
1780
1781 entry->dispatchInProgress = true;
1782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
1785
1786 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001787 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 if (currentTime < entry->interceptKeyWakeupTime) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001789 nextWakeupTime = std::min(nextWakeupTime, entry->interceptKeyWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 return false; // wait until next wakeup
1791 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001792 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 entry->interceptKeyWakeupTime = 0;
1794 }
1795
1796 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001797 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001799 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001800 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001801
1802 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1803 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1804 };
1805 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001806 // Poke user activity for keys not passed to user
1807 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 return false; // wait for the command to run
1809 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001810 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001812 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001813 if (*dropReason == DropReason::NOT_DROPPED) {
1814 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 }
1816 }
1817
1818 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001819 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001820 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1822 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001823 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001824 // Poke user activity for undispatched keys
1825 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 return true;
1827 }
1828
1829 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001830 InputEventInjectionResult injectionResult;
1831 sp<WindowInfoHandle> focusedWindow =
1832 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1833 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001834 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 return false;
1836 }
1837
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001838 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001839 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 return true;
1841 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001842 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1843
1844 std::vector<InputTarget> inputTargets;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001845 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1846 InputTarget::Flags::FOREGROUND, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001848 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001849 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001851 if (mTracer) {
1852 ensureEventTraced(*entry);
1853 for (const auto& target : inputTargets) {
1854 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1855 }
1856 }
1857
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 // Dispatch the key.
1859 dispatchEventLocked(currentTime, entry, inputTargets);
1860 return true;
1861}
1862
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1865 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1866 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1867 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1868 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1869 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1870 entry.metaState, entry.repeatCount, entry.downTime);
1871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872}
1873
Prabir Pradhancef936d2021-07-21 16:17:52 +00001874void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00001875 const std::shared_ptr<const SensorEntry>& entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001876 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001877 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1878 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1879 "source=0x%x, sensorType=%s",
1880 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001881 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001882 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001883 auto command = [this, entry]() REQUIRES(mLock) {
1884 scoped_unlock unlock(mLock);
1885
1886 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001887 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001888 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001889 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1890 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001891 };
1892 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001893}
1894
1895bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001896 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1897 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001898 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001899 }
Chris Yef59a2f42020-10-16 12:55:26 -07001900 { // acquire lock
1901 std::scoped_lock _l(mLock);
1902
1903 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
Prabir Pradhan24047542023-11-02 17:14:59 +00001904 std::shared_ptr<const EventEntry> entry = *it;
Chris Yef59a2f42020-10-16 12:55:26 -07001905 if (entry->type == EventEntry::Type::SENSOR) {
1906 it = mInboundQueue.erase(it);
1907 releaseInboundEventLocked(entry);
1908 }
1909 }
1910 }
1911 return true;
1912}
1913
Prabir Pradhan24047542023-11-02 17:14:59 +00001914bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime,
1915 std::shared_ptr<const MotionEntry> entry,
Siarhei Vishniakou69505962023-12-28 12:07:04 -08001916 DropReason* dropReason, nsecs_t& nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001917 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001919 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 entry->dispatchInProgress = true;
1921
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 }
1924
1925 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001926 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001927 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1929 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 return true;
1931 }
1932
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001933 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
1935 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001936 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 if (isPointerEvent) {
1940 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001941
1942 if (mDragState &&
1943 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1944 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1945 pilferPointersLocked(mDragState->dragWindow->getToken());
1946 }
1947
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001948 inputTargets =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07001949 findTouchedWindowTargetsLocked(currentTime, *entry, /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001950 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1951 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 } else {
1953 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001954 sp<WindowInfoHandle> focusedWindow =
1955 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1956 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1957 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00001958 addWindowTargetLocked(focusedWindow, InputTarget::DispatchMode::AS_IS,
1959 InputTarget::Flags::FOREGROUND, getDownTime(*entry),
1960 inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001963 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 return false;
1965 }
1966
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001967 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001968 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001969 return true;
1970 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001972 CancelationOptions::Mode mode(
1973 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1974 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001975 CancelationOptions options(mode, "input event injection failed");
1976 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 return true;
1978 }
1979
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001980 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001981 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00001983 if (mTracer) {
1984 ensureEventTraced(*entry);
1985 for (const auto& target : inputTargets) {
1986 mTracer->dispatchToTargetHint(*entry->traceTracker, target);
1987 }
1988 }
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // Dispatch the motion.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 dispatchEventLocked(currentTime, entry, inputTargets);
1992 return true;
1993}
1994
chaviw98318de2021-05-19 16:45:23 -05001995void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001996 bool isExiting, const int32_t rawX,
1997 const int32_t rawY) {
1998 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001999 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00002000 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
2001 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08002002
2003 enqueueInboundEventLocked(std::move(dragEntry));
2004}
2005
Prabir Pradhan24047542023-11-02 17:14:59 +00002006void InputDispatcher::dispatchDragLocked(nsecs_t currentTime,
2007 std::shared_ptr<const DragEntry> entry) {
arthurhungb89ccb02020-12-30 16:19:01 +08002008 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
2009 if (channel == nullptr) {
2010 return; // Window has gone away
2011 }
2012 InputTarget target;
2013 target.inputChannel = channel;
arthurhungb89ccb02020-12-30 16:19:01 +08002014 entry->dispatchInProgress = true;
2015 dispatchEventLocked(currentTime, entry, {target});
2016}
2017
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002019 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002020 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002021 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002022 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002023 "metaState=0x%x, buttonState=0x%x,"
2024 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002025 prefix, entry.eventTime, entry.deviceId,
2026 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
2027 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
2028 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2029 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002031 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002032 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002033 "x=%f, y=%f, pressure=%f, size=%f, "
2034 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2035 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002036 i, entry.pointerProperties[i].id,
2037 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002038 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2039 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2040 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2041 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2042 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2043 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2044 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2045 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2046 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049}
2050
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002051void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Prabir Pradhan24047542023-11-02 17:14:59 +00002052 std::shared_ptr<const EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002053 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002055 if (DEBUG_DISPATCH_CYCLE) {
2056 ALOGD("dispatchEventToCurrentInputTargets");
2057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002059 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2062
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002063 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002065 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002066 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002067 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002068 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002069 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 } else {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002071 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2072 LOG(INFO) << "Dropping event delivery to target with channel "
2073 << inputTarget.inputChannel->getName()
2074 << " because it is no longer registered with the input dispatcher.";
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077 }
2078}
2079
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002080void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002081 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2082 // If the policy decides to close the app, we will get a channel removal event via
2083 // unregisterInputChannel, and will clean up the connection that way. We are already not
2084 // sending new pointers to the connection when it blocked, but focused events will continue to
2085 // pile up.
2086 ALOGW("Canceling events for %s because it is unresponsive",
2087 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002088 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002089 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 "application not responding");
2091 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
2093}
2094
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002096 if (DEBUG_FOCUS) {
2097 ALOGD("Resetting ANR timeouts.");
2098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
2100 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002102 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103}
2104
Tiger Huang721e26f2018-07-24 22:26:19 +08002105/**
2106 * Get the display id that the given event should go to. If this event specifies a valid display id,
2107 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2108 * Focused display is the display that the user most recently interacted with.
2109 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002110int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002111 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002112 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002113 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002114 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2115 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002116 break;
2117 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002118 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2120 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 break;
2122 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002123 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002124 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002125 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002126 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002127 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002128 case EventEntry::Type::SENSOR:
2129 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002130 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 return ADISPLAY_ID_NONE;
2132 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002133 }
2134 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2135}
2136
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002137bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2138 const char* focusedWindowName) {
2139 if (mAnrTracker.empty()) {
2140 // already processed all events that we waited for
2141 mKeyIsWaitingForEventsTimeout = std::nullopt;
2142 return false;
2143 }
2144
2145 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2146 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002147 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002148 mKeyIsWaitingForEventsTimeout = currentTime +
2149 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2150 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 return true;
2152 }
2153
2154 // We still have pending events, and already started the timer
2155 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2156 return true; // Still waiting
2157 }
2158
2159 // Waited too long, and some connection still hasn't processed all motions
2160 // Just send the key to the focused window
2161 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2162 focusedWindowName);
2163 mKeyIsWaitingForEventsTimeout = std::nullopt;
2164 return false;
2165}
2166
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002167sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002168 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002169 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002170 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
Tiger Huang721e26f2018-07-24 22:26:19 +08002172 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002173 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002174 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002175 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2176
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 // If there is no currently focused window and no focused application
2178 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2180 ALOGI("Dropping %s event because there is no focused window or focused application in "
2181 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002182 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185
Vishnu Nair062a8672021-09-03 16:07:44 -07002186 // Drop key events if requested by input feature
2187 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002189 }
2190
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2192 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2193 // start interacting with another application via touch (app switch). This code can be removed
2194 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2195 // an app is expected to have a focused window.
2196 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2197 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2198 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002199 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2200 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2201 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002202 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002203 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002204 ALOGW("Waiting because no window has focus but %s may eventually add a "
2205 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002206 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002207 nextWakeupTime = std::min(nextWakeupTime, *mNoFocusedWindowTimeoutTime);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002208 outInjectionResult = InputEventInjectionResult::PENDING;
2209 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002210 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2211 // Already raised ANR. Drop the event
2212 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002213 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002214 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002215 } else {
2216 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217 outInjectionResult = InputEventInjectionResult::PENDING;
2218 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002219 }
2220 }
2221
2222 // we have a valid, non-null focused window
2223 resetNoFocusedWindowTimeoutLocked();
2224
Prabir Pradhan5735a322022-04-11 17:23:34 +00002225 // Verify targeted injection.
2226 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2227 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002228 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2229 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002232 if (focusedWindowHandle->getInfo()->inputConfig.test(
2233 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002235 outInjectionResult = InputEventInjectionResult::PENDING;
2236 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 }
2238
2239 // If the event is a key event, then we must wait for all previous events to
2240 // complete before delivering it because previous events may have the
2241 // side-effect of transferring focus to a different window and we want to
2242 // ensure that the following keys are sent to the new window.
2243 //
2244 // Suppose the user touches a button in a window then immediately presses "A".
2245 // If the button causes a pop-up window to appear then we want to ensure that
2246 // the "A" key is delivered to the new pop-up window. This is because users
2247 // often anticipate pending UI changes when typing on a keyboard.
2248 // To obtain this behavior, we must serialize key events with respect to all
2249 // prior input events.
2250 if (entry.type == EventEntry::Type::KEY) {
2251 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
Siarhei Vishniakou69505962023-12-28 12:07:04 -08002252 nextWakeupTime = std::min(nextWakeupTime, *mKeyIsWaitingForEventsTimeout);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = InputEventInjectionResult::PENDING;
2254 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 }
2257
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002258 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2259 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260}
2261
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262/**
2263 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2264 * that are currently unresponsive.
2265 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002266std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2267 const std::vector<Monitor>& monitors) const {
2268 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002270 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002271 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002272 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 if (connection == nullptr) {
2274 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002275 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002276 return false;
2277 }
2278 if (!connection->responsive) {
2279 ALOGW("Unresponsive monitor %s will not get the new gesture",
2280 connection->inputChannel->getName().c_str());
2281 return false;
2282 }
2283 return true;
2284 });
2285 return responsiveMonitors;
2286}
2287
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002288std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002289 nsecs_t currentTime, const MotionEntry& entry,
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002290 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002291 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002293 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 // For security reasons, we defer updating the touch state until we are sure that
2295 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 const int32_t displayId = entry.displayId;
2297 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002298 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299
2300 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002301 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 // Copy current touch state into tempTouchState.
2304 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2305 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002306 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2309 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002310 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002311 }
2312
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002313 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002314
2315 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2316 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2317 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002318 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2319 // touchable windows.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002320 const bool wasDown = oldState != nullptr && oldState->isDown(entry.deviceId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002321 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2322 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002323 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2324 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2325 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002326 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002327
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002328 if (newGesture) {
2329 isSplit = false;
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002330 }
2331
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002332 if (isDown && tempTouchState.hasHoveringPointers(entry.deviceId)) {
2333 // Compatibility behaviour: ACTION_DOWN causes HOVER_EXIT to get generated.
2334 tempTouchState.clearHoveringPointers(entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002337 if (isHoverAction) {
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002338 if (wasDown) {
2339 // Started hovering, but the device is already down: reject the hover event
2340 LOG(ERROR) << "Got hover event " << entry.getDescription()
2341 << " but the device is already down " << oldState->dump();
2342 outInjectionResult = InputEventInjectionResult::FAILED;
2343 return {};
2344 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002345 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2346 // all of the existing hovering pointers and recompute.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002347 tempTouchState.clearHoveringPointers(entry.deviceId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002348 }
2349
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2351 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002352 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002353 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002354 const PointerProperties& pointer = entry.pointerProperties[pointerIndex];
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002355 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2356 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002357 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002358 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002359 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002360
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002361 if (isDown) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002362 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002365 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002366 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002368 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002369 }
2370
Prabir Pradhan5735a322022-04-11 17:23:34 +00002371 // Verify targeted injection.
2372 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2373 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002374 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002375 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002376 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002377 }
2378
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002379 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002380 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002381 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2382 // New window supports splitting, but we should never split mouse events.
2383 isSplit = !isFromMouse;
2384 } else if (isSplit) {
2385 // New window does not support splitting but we have already split events.
2386 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002387 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2388 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002389 newTouchedWindowHandle = nullptr;
2390 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002391 } else {
2392 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002393 // be delivered to a new window which supports split touch. Pointers from a mouse device
2394 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002395 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002396 }
2397
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002398 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002399 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002401 // Process the foreground window first so that it is the first to receive the event.
2402 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002403 }
2404
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002405 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002406 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2407 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002408 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002409 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002410 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002411 }
2412
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002414 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002415 continue;
2416 }
2417
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002418 if (isHoverAction) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002419 // The "windowHandle" is the target of this hovering pointer.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002420 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointer);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002421 }
2422
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 // Set target flags.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002424 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002426 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2427 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002428 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002429 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002430
2431 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002432 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002433 }
2434 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002435 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002437 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002438 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002439
2440 // Update the temporary touch state.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002441
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002442 if (!isHoverAction) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002443 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2444 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002445 tempTouchState.addOrUpdateWindow(windowHandle, InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002446 targetFlags, entry.deviceId, {pointer},
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002447 isDownOrPointerDown
2448 ? std::make_optional(entry.eventTime)
2449 : std::nullopt);
2450 // If this is the pointer going down and the touched window has a wallpaper
2451 // then also add the touched wallpaper windows so they are locked in for the
2452 // duration of the touch gesture. We do not collect wallpapers during HOVER_MOVE or
2453 // SCROLL because the wallpaper engine only supports touch events. We would need to
2454 // add a mechanism similar to View.onGenericMotionEvent to enable wallpapers to
2455 // handle these events.
2456 if (isDownOrPointerDown && targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Arthur Hungc539dbb2022-12-08 07:45:36 +00002457 windowHandle->getInfo()->inputConfig.test(
2458 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2459 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2460 if (wallpaper != nullptr) {
2461 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2462 InputTarget::Flags::WINDOW_IS_OBSCURED |
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002463 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Arthur Hungc539dbb2022-12-08 07:45:36 +00002464 if (isSplit) {
2465 wallpaperFlags |= InputTarget::Flags::SPLIT;
2466 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002467 tempTouchState.addOrUpdateWindow(wallpaper,
2468 InputTarget::DispatchMode::AS_IS,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002469 wallpaperFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002470 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002471 }
2472 }
2473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002475
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002476 // If a window is already pilfering some pointers, give it this new pointer as well and
2477 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2478 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002479 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002480 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointer.id) &&
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002481 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002482 // This window is already pilfering some pointers, and this new pointer is also
2483 // going to it. Therefore, take over this pointer and don't give it to anyone
2484 // else.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002485 touchedWindow.addPilferingPointer(entry.deviceId, pointer.id);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002486 }
2487 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002488
2489 // Restrict all pilfered pointers to the pilfering windows.
2490 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 } else {
2492 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2493
2494 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002495 if (!tempTouchState.isDown(entry.deviceId) &&
2496 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakou31dd1552023-10-30 18:46:10 -07002497 if (DEBUG_DROPPED_EVENTS_VERBOSE) {
2498 LOG(INFO) << "Dropping event because the pointer for device " << entry.deviceId
2499 << " is not down or we previously dropped the pointer down event in "
2500 << "display " << displayId << ": " << entry.getDescription();
2501 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002502 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002503 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002506 // If the pointer is not currently hovering, then ignore the event.
2507 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2508 const int32_t pointerId = entry.pointerProperties[0].id;
2509 if (oldState == nullptr ||
2510 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2511 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2512 "display "
2513 << displayId << ": " << entry.getDescription();
2514 outInjectionResult = InputEventInjectionResult::FAILED;
2515 return {};
2516 }
2517 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2518 }
2519
arthurhung6d4bed92021-03-17 11:59:33 +08002520 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002521
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002523 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002524 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002525 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002526 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002527 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002528 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002529 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002530 sp<WindowInfoHandle> newTouchedWindowHandle =
2531 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002532
Prabir Pradhan5735a322022-04-11 17:23:34 +00002533 // Verify targeted injection.
2534 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2535 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002536 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002537 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002538 }
2539
Vishnu Nair062a8672021-09-03 16:07:44 -07002540 // Drop touch events if requested by input feature
2541 if (newTouchedWindowHandle != nullptr &&
2542 shouldDropInput(entry, newTouchedWindowHandle)) {
2543 newTouchedWindowHandle = nullptr;
2544 }
2545
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002546 if (newTouchedWindowHandle != nullptr &&
2547 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002548 ALOGI("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002549 oldTouchedWindowHandle->getName().c_str(),
2550 newTouchedWindowHandle->getName().c_str(), displayId);
2551
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002553 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002554 const PointerProperties& pointer = entry.pointerProperties[0];
2555 pointerIds.set(pointer.id);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002556
2557 const TouchedWindow& touchedWindow =
2558 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002559 addPointerWindowTargetLocked(oldTouchedWindowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002560 InputTarget::DispatchMode::SLIPPERY_EXIT,
2561 ftl::Flags<InputTarget::Flags>(), pointerIds,
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002562 touchedWindow.getDownTimeInTarget(entry.deviceId),
2563 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564
2565 // Make a slippery entrance into the new window.
2566 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002567 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002570 ftl::Flags<InputTarget::Flags> targetFlags;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002571 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002572 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002575 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 }
2577 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002578 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002579 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002580 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002583 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle,
2584 InputTarget::DispatchMode::SLIPPERY_ENTER,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002585 targetFlags, entry.deviceId, {pointer},
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002586 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002587
2588 // Check if the wallpaper window should deliver the corresponding event.
2589 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002590 tempTouchState, entry.deviceId, pointer, targets);
2591 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointer.id,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002592 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
2594 }
Arthur Hung96483742022-11-15 03:30:48 +00002595
2596 // Update the pointerIds for non-splittable when it received pointer down.
2597 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2598 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002599 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002600 std::vector<PointerProperties> touchingPointers{entry.pointerProperties[pointerIndex]};
2601 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Arthur Hung96483742022-11-15 03:30:48 +00002602 // Ignore drag window for it should just track one pointer.
2603 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2604 continue;
2605 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002606 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002607 }
2608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
2610
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002611 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002612 {
2613 std::vector<TouchedWindow> hoveringWindows =
2614 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2615 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002616 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002617 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
2618 touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002619 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002620 if (!target) {
2621 continue;
2622 }
2623 // Hardcode to single hovering pointer for now.
2624 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2625 pointerIds.set(entry.pointerProperties[0].id);
2626 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2627 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630
Prabir Pradhan5735a322022-04-11 17:23:34 +00002631 // Ensure that all touched windows are valid for injection.
2632 if (entry.injectionState != nullptr) {
2633 std::string errs;
2634 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002635 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2636 if (err) errs += "\n - " + *err;
2637 }
2638 if (!errs.empty()) {
2639 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002640 "%s:%s",
2641 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002642 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002643 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002644 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002645 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002646
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002647 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2648 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002650 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002651 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002652 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002653 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002654 for (InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002655 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002656 sp<WindowInfoHandle> targetWindow =
2657 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2658 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2659 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 }
2662 }
2663 }
2664 }
2665
Harry Cuttsb166c002023-05-09 13:06:05 +00002666 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2667 // only want the system UI to handle these gestures.
2668 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2669 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2670 if (isTouchpadNavGesture) {
2671 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2672 }
2673
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002674 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002675 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002676 std::vector<PointerProperties> touchingPointers =
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002677 touchedWindow.getTouchingPointers(entry.deviceId);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002678 if (touchingPointers.empty()) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002679 continue;
2680 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002681 addPointerWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.dispatchMode,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08002682 touchedWindow.targetFlags, getPointerIds(touchingPointers),
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002683 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002684 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002685
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002686 // During targeted injection, only allow owned targets to receive events
2687 std::erase_if(targets, [&](const InputTarget& target) {
2688 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2689 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2690 if (err) {
2691 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2692 << ": " << (*err);
2693 return true;
2694 }
2695 return false;
2696 });
2697
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002698 if (targets.empty()) {
2699 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2700 outInjectionResult = InputEventInjectionResult::FAILED;
2701 return {};
2702 }
2703
2704 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2705 // window that is actually receiving the entire gesture.
2706 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002707 return target.dispatchMode == InputTarget::DispatchMode::OUTSIDE;
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002708 })) {
2709 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2710 << entry.getDescription();
2711 outInjectionResult = InputEventInjectionResult::FAILED;
2712 return {};
2713 }
2714
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002715 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716
Prabir Pradhan502a7252023-12-01 16:11:24 +00002717 // Now that we have generated all of the input targets for this event, reset the dispatch
2718 // mode for all touched window to AS_IS.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002719 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan502a7252023-12-01 16:11:24 +00002720 touchedWindow.dispatchMode = InputTarget::DispatchMode::AS_IS;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002721 }
2722
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002723 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7be50c92023-11-17 17:09:08 -08002724 if (maskedAction == AMOTION_EVENT_ACTION_UP) {
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002725 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002726 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002727 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002728 // All pointers up or canceled.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002729 tempTouchState.removeAllPointersForDevice(entry.deviceId);
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002730 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2731 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002732 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2733 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2734 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 }
2736
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 // Save changes unless the action was scroll in which case the temporary touch
2738 // state was only valid for this one action.
2739 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002740 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002741 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002742 mTouchStatesByDisplay[displayId] = tempTouchState;
2743 } else {
2744 mTouchStatesByDisplay.erase(displayId);
2745 }
2746 }
2747
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002748 if (tempTouchState.windows.empty()) {
2749 mTouchStatesByDisplay.erase(displayId);
2750 }
2751
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002752 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753}
2754
arthurhung6d4bed92021-03-17 11:59:33 +08002755void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002756 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2757 // have an explicit reason to support it.
2758 constexpr bool isStylus = false;
2759
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002760 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002761 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002762 if (dropWindow) {
2763 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002764 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002765 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002766 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002767 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002768 }
2769 mDragState.reset();
2770}
2771
2772void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002773 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002774 return;
2775 }
2776
arthurhung6d4bed92021-03-17 11:59:33 +08002777 if (!mDragState->isStartDrag) {
2778 mDragState->isStartDrag = true;
2779 mDragState->isStylusButtonDownAtStart =
2780 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2781 }
2782
Arthur Hung54745652022-04-20 07:17:41 +00002783 // Find the pointer index by id.
2784 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002785 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002786 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2787 if (pointerProperties.id == mDragState->pointerId) {
2788 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002789 }
Arthur Hung54745652022-04-20 07:17:41 +00002790 }
arthurhung6d4bed92021-03-17 11:59:33 +08002791
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002792 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002793 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002794 }
2795
2796 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2797 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2798 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2799
2800 switch (maskedAction) {
2801 case AMOTION_EVENT_ACTION_MOVE: {
2802 // Handle the special case : stylus button no longer pressed.
2803 bool isStylusButtonDown =
2804 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2805 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2806 finishDragAndDrop(entry.displayId, x, y);
2807 return;
2808 }
2809
2810 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2811 // until we have an explicit reason to support it.
2812 constexpr bool isStylus = false;
2813
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002814 sp<WindowInfoHandle> hoverWindowHandle =
2815 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2816 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002817 // enqueue drag exit if needed.
2818 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2819 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2820 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002821 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002822 y);
2823 }
2824 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2825 }
2826 // enqueue drag location if needed.
2827 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002828 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002829 }
2830 break;
2831 }
2832
2833 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002834 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002835 break;
2836 }
2837 // The drag pointer is up.
2838 [[fallthrough]];
2839 case AMOTION_EVENT_ACTION_UP:
2840 finishDragAndDrop(entry.displayId, x, y);
2841 break;
2842 case AMOTION_EVENT_ACTION_CANCEL: {
2843 ALOGD("Receiving cancel when drag and drop.");
2844 sendDropWindowCommandLocked(nullptr, 0, 0);
2845 mDragState.reset();
2846 break;
2847 }
arthurhungb89ccb02020-12-30 16:19:01 +08002848 }
2849}
2850
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002851std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2852 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002853 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002854 std::optional<nsecs_t> firstDownTimeInTarget) const {
2855 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2856 if (inputChannel == nullptr) {
2857 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2858 return {};
2859 }
2860 InputTarget inputTarget;
2861 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002862 inputTarget.windowHandle = windowHandle;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002863 inputTarget.dispatchMode = dispatchMode;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002864 inputTarget.flags = targetFlags;
2865 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2866 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2867 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2868 if (displayInfoIt != mDisplayInfos.end()) {
2869 inputTarget.displayTransform = displayInfoIt->second.transform;
2870 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002871 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2873 }
2874 return inputTarget;
2875}
2876
chaviw98318de2021-05-19 16:45:23 -05002877void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002878 InputTarget::DispatchMode dispatchMode,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002879 ftl::Flags<InputTarget::Flags> targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002880 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002881 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002882 std::vector<InputTarget>::iterator it =
2883 std::find_if(inputTargets.begin(), inputTargets.end(),
2884 [&windowHandle](const InputTarget& inputTarget) {
2885 return inputTarget.inputChannel->getConnectionToken() ==
2886 windowHandle->getToken();
2887 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002888
chaviw98318de2021-05-19 16:45:23 -05002889 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002890
2891 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002892 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002893 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2894 firstDownTimeInTarget);
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002895 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002896 return;
2897 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002898 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002899 it = inputTargets.end() - 1;
2900 }
2901
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002902 if (it->flags != targetFlags) {
2903 LOG(ERROR) << "Flags don't match! targetFlags=" << targetFlags.string() << ", it=" << *it;
2904 }
2905 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
2906 LOG(ERROR) << "Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
2907 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2908 }
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002909}
2910
2911void InputDispatcher::addPointerWindowTargetLocked(
2912 const sp<android::gui::WindowInfoHandle>& windowHandle,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002913 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags,
2914 std::bitset<MAX_POINTER_ID + 1> pointerIds, std::optional<nsecs_t> firstDownTimeInTarget,
2915 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002916 if (pointerIds.none()) {
2917 for (const auto& target : inputTargets) {
2918 LOG(INFO) << "Target: " << target;
2919 }
2920 LOG(FATAL) << "No pointers specified for " << windowHandle->getName();
2921 return;
2922 }
2923 std::vector<InputTarget>::iterator it =
2924 std::find_if(inputTargets.begin(), inputTargets.end(),
2925 [&windowHandle](const InputTarget& inputTarget) {
2926 return inputTarget.inputChannel->getConnectionToken() ==
2927 windowHandle->getToken();
2928 });
2929
2930 // This is a hack, because the actual entry could potentially be an ACTION_DOWN event that
2931 // causes a HOVER_EXIT to be generated. That means that the same entry of ACTION_DOWN would
2932 // have DISPATCH_AS_HOVER_EXIT and DISPATCH_AS_IS. And therefore, we have to create separate
2933 // input targets for hovering pointers and for touching pointers.
2934 // If we picked an existing input target above, but it's for HOVER_EXIT - let's use a new
2935 // target instead.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002936 if (it != inputTargets.end() && it->dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002937 // Force the code below to create a new input target
2938 it = inputTargets.end();
2939 }
2940
2941 const WindowInfo* windowInfo = windowHandle->getInfo();
2942
2943 if (it == inputTargets.end()) {
2944 std::optional<InputTarget> target =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002945 createInputTargetLocked(windowHandle, dispatchMode, targetFlags,
2946 firstDownTimeInTarget);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07002947 if (!target) {
2948 return;
2949 }
2950 inputTargets.push_back(*target);
2951 it = inputTargets.end() - 1;
2952 }
2953
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002954 if (it->dispatchMode != dispatchMode) {
2955 LOG(ERROR) << __func__ << ": DispatchMode doesn't match! ignoring new mode="
2956 << ftl::enum_string(dispatchMode) << ", it=" << *it;
2957 }
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002958 if (it->flags != targetFlags) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002959 LOG(ERROR) << __func__ << ": Flags don't match! new targetFlags=" << targetFlags.string()
2960 << ", it=" << *it;
Siarhei Vishniakou4bd0b7c2023-10-27 00:51:14 -07002961 }
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002962 if (it->globalScaleFactor != windowInfo->globalScaleFactor) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00002963 LOG(ERROR) << __func__ << ": Mismatch! it->globalScaleFactor=" << it->globalScaleFactor
Siarhei Vishniakou23d73fb2023-10-29 13:27:46 -07002964 << ", windowInfo->globalScaleFactor=" << windowInfo->globalScaleFactor;
2965 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002966
chaviw1ff3d1e2020-07-01 15:53:47 -07002967 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968}
2969
Michael Wright3dd60e22019-03-27 22:06:44 +00002970void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002971 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002972 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2973 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002974
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002975 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2976 InputTarget target;
2977 target.inputChannel = monitor.inputChannel;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002978 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2979 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002980 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2981 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002982 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002983 target.setDefaultPointerTransform(target.displayTransform);
2984 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985 }
2986}
2987
Robert Carrc9bf1d32020-04-13 17:21:08 -07002988/**
2989 * Indicate whether one window handle should be considered as obscuring
2990 * another window handle. We only check a few preconditions. Actually
2991 * checking the bounds is left to the caller.
2992 */
chaviw98318de2021-05-19 16:45:23 -05002993static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2994 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002995 // Compare by token so cloned layers aren't counted
2996 if (haveSameToken(windowHandle, otherHandle)) {
2997 return false;
2998 }
2999 auto info = windowHandle->getInfo();
3000 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003001 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003002 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003003 } else if (otherInfo->alpha == 0 &&
3004 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003005 // Those act as if they were invisible, so we don't need to flag them.
3006 // We do want to potentially flag touchable windows even if they have 0
3007 // opacity, since they can consume touches and alter the effects of the
3008 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003009 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00003010 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
3011 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00003012 } else if (info->ownerUid == otherInfo->ownerUid) {
3013 // If ownerUid is the same we don't generate occlusion events as there
3014 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07003015 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003016 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003017 return false;
3018 } else if (otherInfo->displayId != info->displayId) {
3019 return false;
3020 }
3021 return true;
3022}
3023
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003024/**
3025 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
3026 * untrusted, one should check:
3027 *
3028 * 1. If result.hasBlockingOcclusion is true.
3029 * If it's, it means the touch should be blocked due to a window with occlusion mode of
3030 * BLOCK_UNTRUSTED.
3031 *
3032 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
3033 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
3034 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
3035 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
3036 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
3037 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
3038 *
3039 * If neither of those is true, then it means the touch can be allowed.
3040 */
3041InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05003042 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
3043 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003044 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05003045 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003046 TouchOcclusionInfo info;
3047 info.hasBlockingOcclusion = false;
3048 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 info.obscuringUid = gui::Uid::INVALID;
3050 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05003051 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003052 if (windowHandle == otherHandle) {
3053 break; // All future windows are below us. Exit early.
3054 }
chaviw98318de2021-05-19 16:45:23 -05003055 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003056 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3057 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003058 if (DEBUG_TOUCH_OCCLUSION) {
3059 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003060 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003061 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003062 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3063 // we perform the checks below to see if the touch can be propagated or not based on the
3064 // window's touch occlusion mode
3065 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3066 info.hasBlockingOcclusion = true;
3067 info.obscuringUid = otherInfo->ownerUid;
3068 info.obscuringPackage = otherInfo->packageName;
3069 break;
3070 }
3071 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003072 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003073 float opacity =
3074 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3075 // Given windows A and B:
3076 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3077 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3078 opacityByUid[uid] = opacity;
3079 if (opacity > info.obscuringOpacity) {
3080 info.obscuringOpacity = opacity;
3081 info.obscuringUid = uid;
3082 info.obscuringPackage = otherInfo->packageName;
3083 }
3084 }
3085 }
3086 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003087 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003088 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003089 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003090 return info;
3091}
3092
chaviw98318de2021-05-19 16:45:23 -05003093std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003094 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003095 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003096 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3097 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3098 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003099 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003100 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003101 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3102 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003103 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3104 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3105 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003106 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003107}
3108
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003109bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3110 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003111 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3112 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003113 return false;
3114 }
3115 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003116 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003117 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003118 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003119 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3120 return false;
3121 }
3122 return true;
3123}
3124
chaviw98318de2021-05-19 16:45:23 -05003125bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003128 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3129 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003130 if (windowHandle == otherHandle) {
3131 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
chaviw98318de2021-05-19 16:45:23 -05003133 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003134 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003135 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 return true;
3137 }
3138 }
3139 return false;
3140}
3141
chaviw98318de2021-05-19 16:45:23 -05003142bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003143 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003144 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3145 const WindowInfo* windowInfo = windowHandle->getInfo();
3146 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003147 if (windowHandle == otherHandle) {
3148 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003149 }
chaviw98318de2021-05-19 16:45:23 -05003150 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003151 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003152 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003153 return true;
3154 }
3155 }
3156 return false;
3157}
3158
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003159std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003160 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003161 if (applicationHandle != nullptr) {
3162 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003163 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 } else {
3165 return applicationHandle->getName();
3166 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003167 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003168 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
3172}
3173
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003174void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003175 if (!isUserActivityEvent(eventEntry)) {
3176 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003177 return;
3178 }
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003179
3180 const int32_t eventType = getUserActivityEventType(eventEntry);
3181 if (input_flags::rate_limit_user_activity_poke_in_dispatcher()) {
3182 // Note that we're directly getting the time diff between the current event and the previous
3183 // event. This is assuming that the first user event always happens at a timestamp that is
3184 // greater than `mMinTimeBetweenUserActivityPokes` (otherwise, the first user event will
3185 // wrongly be dropped). In real life, `mMinTimeBetweenUserActivityPokes` is a much smaller
3186 // value than the potential first user activity event time, so this is ok.
3187 std::chrono::nanoseconds timeSinceLastEvent =
3188 std::chrono::nanoseconds(eventEntry.eventTime - mLastUserActivityTimes[eventType]);
3189 if (timeSinceLastEvent < mMinTimeBetweenUserActivityPokes) {
3190 return;
3191 }
3192 }
3193
Tiger Huang721e26f2018-07-24 22:26:19 +08003194 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003195 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003196 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003197 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003198 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003199 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003200 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202 }
3203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003205 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3207 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 return;
3209 }
Josep del Riob3981622023-04-18 15:49:45 +00003210 if (windowDisablingUserActivityInfo != nullptr) {
3211 if (DEBUG_DISPATCH_CYCLE) {
3212 ALOGD("Not poking user activity: disabled by window '%s'.",
3213 windowDisablingUserActivityInfo->name.c_str());
3214 }
3215 return;
3216 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003219 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3221 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 return;
3223 }
Josep del Riob3981622023-04-18 15:49:45 +00003224 // If the key code is unknown, we don't consider it user activity
3225 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3226 return;
3227 }
3228 // Don't inhibit events that were intercepted or are not passed to
3229 // the apps, like system shortcuts
3230 if (windowDisablingUserActivityInfo != nullptr &&
3231 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3232 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3233 if (DEBUG_DISPATCH_CYCLE) {
3234 ALOGD("Not poking user activity: disabled by window '%s'.",
3235 windowDisablingUserActivityInfo->name.c_str());
3236 }
3237 return;
3238 }
3239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003242 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003243 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003244 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003245 break;
3246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
3248
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08003249 mLastUserActivityTimes[eventType] = eventEntry.eventTime;
Prabir Pradhancef936d2021-07-21 16:17:52 +00003250 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3251 REQUIRES(mLock) {
3252 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003253 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003254 };
3255 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256}
3257
3258void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003259 const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003260 std::shared_ptr<const EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003261 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003262 ATRACE_NAME_IF(ATRACE_ENABLED(),
3263 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3264 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003265 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003266 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003267 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003268 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003269 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003270 inputTarget.getPointerInfoString().c_str());
3271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 // Skip this event if the connection status is not normal.
3274 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003275 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003276 if (DEBUG_DISPATCH_CYCLE) {
3277 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003278 connection->getInputChannelName().c_str(),
3279 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 return;
3282 }
3283
3284 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003286 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003287 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003288 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003290 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003291 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003292 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3293 logDispatchStateLocked();
3294 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3295 "target on connection "
3296 << connection->getInputChannelName() << " for "
3297 << originalMotionEntry.getDescription();
3298 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003300 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3301 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 if (!splitMotionEntry) {
3303 return; // split event was dropped
3304 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003305 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3306 std::string reason = std::string("reason=pointer cancel on split window");
3307 android_log_event_list(LOGTAG_INPUT_CANCEL)
3308 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3309 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003310 if (DEBUG_FOCUS) {
3311 ALOGD("channel '%s' ~ Split motion event.",
3312 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003313 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003314 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003315 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection,
3316 std::move(splitMotionEntry),
3317 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 return;
3319 }
3320 }
3321
3322 // Not splitting. Enqueue dispatch entries for the event as is.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003323 enqueueDispatchEntryAndStartDispatchCycleLocked(currentTime, connection, eventEntry,
3324 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325}
3326
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003327void InputDispatcher::enqueueDispatchEntryAndStartDispatchCycleLocked(
3328 nsecs_t currentTime, const std::shared_ptr<Connection>& connection,
3329 std::shared_ptr<const EventEntry> eventEntry, const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003330 ATRACE_NAME_IF(ATRACE_ENABLED(),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003331 StringPrintf("enqueueDispatchEntryAndStartDispatchCycleLocked(inputChannel=%s, "
3332 "id=0x%" PRIx32 ")",
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003333 connection->getInputChannelName().c_str(), eventEntry->id));
Michael Wright3dd60e22019-03-27 22:06:44 +00003334
hongzuo liu95785e22022-09-06 02:51:35 +00003335 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003337 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
3339 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003340 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 startDispatchCycleLocked(currentTime, connection);
3342 }
3343}
3344
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003345void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Prabir Pradhan24047542023-11-02 17:14:59 +00003346 std::shared_ptr<const EventEntry> eventEntry,
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003347 const InputTarget& inputTarget) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 // This is a new event.
3349 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003350 std::unique_ptr<DispatchEntry> dispatchEntry =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003351 createDispatchEntry(inputTarget, eventEntry, inputTarget.flags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003353 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3354 // different EventEntry than what was passed in.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003355 eventEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 // Apply target flags and update the connection's input state.
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003357 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003358 case EventEntry::Type::KEY: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003359 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
3360 if (!connection->inputState.trackKey(keyEntry, keyEntry.flags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003361 LOG(WARNING) << "channel " << connection->getInputChannelName()
3362 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 return; // skip the inconsistent event
3364 }
3365 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003368 case EventEntry::Type::MOTION: {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003369 std::shared_ptr<const MotionEntry> resolvedMotion =
3370 std::static_pointer_cast<const MotionEntry>(eventEntry);
3371 {
3372 // Determine the resolved motion entry.
3373 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
3374 int32_t resolvedAction = motionEntry.action;
3375 int32_t resolvedFlags = motionEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003377 if (inputTarget.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003378 resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003379 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003380 resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003381 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::HOVER_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003382 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003383 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_EXIT) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003384 resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003385 } else if (inputTarget.dispatchMode == InputTarget::DispatchMode::SLIPPERY_ENTER) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003386 resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3387 }
3388 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
3389 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3390 motionEntry.displayId)) {
3391 if (DEBUG_DISPATCH_CYCLE) {
3392 LOG(DEBUG) << "channel '" << connection->getInputChannelName().c_str()
3393 << "' ~ enqueueDispatchEntryLocked: filling in missing hover "
3394 "enter event";
3395 }
3396 resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3397 }
3398
3399 if (resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3400 resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3401 }
3402 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
3403 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3404 }
3405 if (dispatchEntry->targetFlags.test(
3406 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
3407 resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3408 }
3409
3410 dispatchEntry->resolvedFlags = resolvedFlags;
3411 if (resolvedAction != motionEntry.action) {
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003412 std::optional<std::vector<PointerProperties>> usingProperties;
3413 std::optional<std::vector<PointerCoords>> usingCoords;
3414 if (resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT ||
3415 resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3416 // This is a HOVER_EXIT or an ACTION_CANCEL event that was synthesized by
3417 // the dispatcher, and therefore the coordinates of this event are currently
3418 // incorrect. These events should use the coordinates of the last dispatched
3419 // ACTION_MOVE or HOVER_MOVE. We need to query InputState to get this data.
3420 const bool hovering = resolvedAction == AMOTION_EVENT_ACTION_HOVER_EXIT;
3421 std::optional<std::pair<std::vector<PointerProperties>,
3422 std::vector<PointerCoords>>>
3423 pointerInfo =
3424 connection->inputState.getPointersOfLastEvent(motionEntry,
3425 hovering);
3426 if (pointerInfo) {
3427 usingProperties = pointerInfo->first;
3428 usingCoords = pointerInfo->second;
3429 }
3430 }
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003431 // Generate a new MotionEntry with a new eventId using the resolved action and
3432 // flags.
Siarhei Vishniakoue9ef6bc2023-12-21 19:47:20 -08003433 resolvedMotion = std::make_shared<
3434 MotionEntry>(mIdGenerator.nextId(), motionEntry.injectionState,
3435 motionEntry.eventTime, motionEntry.deviceId,
3436 motionEntry.source, motionEntry.displayId,
3437 motionEntry.policyFlags, resolvedAction,
3438 motionEntry.actionButton, resolvedFlags,
3439 motionEntry.metaState, motionEntry.buttonState,
3440 motionEntry.classification, motionEntry.edgeFlags,
3441 motionEntry.xPrecision, motionEntry.yPrecision,
3442 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3443 motionEntry.downTime,
3444 usingProperties.value_or(motionEntry.pointerProperties),
3445 usingCoords.value_or(motionEntry.pointerCoords));
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003446 if (ATRACE_ENABLED()) {
3447 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3448 ") to MotionEvent(id=0x%" PRIx32 ").",
3449 motionEntry.id, resolvedMotion->id);
3450 ATRACE_NAME(message.c_str());
3451 }
3452
3453 // Set the resolved motion entry in the DispatchEntry.
3454 dispatchEntry->eventEntry = resolvedMotion;
3455 eventEntry = resolvedMotion;
3456 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003459 // Check if we need to cancel any of the ongoing gestures. We don't support multiple
3460 // devices being active at the same time in the same window, so if a new device is
3461 // active, cancel the gesture from the old device.
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003462 std::unique_ptr<EventEntry> cancelEvent =
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003463 connection->inputState.cancelConflictingInputStream(*resolvedMotion);
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003464 if (cancelEvent != nullptr) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003465 LOG(INFO) << "Canceling pointers for device " << resolvedMotion->deviceId << " in "
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003466 << connection->getInputChannelName() << " with event "
3467 << cancelEvent->getDescription();
3468 std::unique_ptr<DispatchEntry> cancelDispatchEntry =
3469 createDispatchEntry(inputTarget, std::move(cancelEvent),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003470 ftl::Flags<InputTarget::Flags>());
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07003471
3472 // Send these cancel events to the queue before sending the event from the new
3473 // device.
3474 connection->outboundQueue.emplace_back(std::move(cancelDispatchEntry));
3475 }
3476
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003477 if (!connection->inputState.trackMotion(*resolvedMotion,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003478 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003479 LOG(WARNING) << "channel " << connection->getInputChannelName()
3480 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003481 return; // skip the inconsistent event
3482 }
3483
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003484 if ((resolvedMotion->flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3485 (resolvedMotion->policyFlags & POLICY_FLAG_TRUSTED)) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003486 // Skip reporting pointer down outside focus to the policy.
3487 break;
3488 }
3489
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003490 dispatchPointerDownOutsideFocus(resolvedMotion->source, resolvedMotion->action,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003491 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003492
3493 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003495 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003496 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003497 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3498 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003499 break;
3500 }
Chris Yef59a2f42020-10-16 12:55:26 -07003501 case EventEntry::Type::SENSOR: {
3502 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3503 break;
3504 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003505 case EventEntry::Type::CONFIGURATION_CHANGED:
3506 case EventEntry::Type::DEVICE_RESET: {
3507 LOG_ALWAYS_FATAL("%s events should not go to apps",
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003508 ftl::enum_string(eventEntry->type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003509 break;
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512
3513 // Remember that we are waiting for this dispatch to complete.
3514 if (dispatchEntry->hasForegroundTarget()) {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003515 incrementPendingForegroundDispatches(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 }
3517
3518 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003519 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003520 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003521}
3522
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003523/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003524 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003525 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003526 * The first role is to log input interaction with windows, which helps determine what the user was
3527 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3528 * that user started interacting with launcher window, as well as any other window that received
3529 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3530 * when the set of tokens that received the event changes. It is not logged again as long as the
3531 * user is interacting with the same windows.
3532 *
3533 * The second role is to track input device activity for metrics collection. For each input event,
3534 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3535 * input_interaction logs, the device interaction is reported even when the set of interaction
3536 * tokens do not change.
3537 *
3538 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3539 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003540 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003541void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3542 const std::vector<InputTarget>& targets) {
3543 int32_t deviceId;
3544 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003545 // Skip ACTION_UP events, and all events other than keys and motions
3546 if (entry.type == EventEntry::Type::KEY) {
3547 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3548 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3549 return;
3550 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003551 deviceId = keyEntry.deviceId;
3552 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003553 } else if (entry.type == EventEntry::Type::MOTION) {
3554 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3555 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003556 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3557 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003558 return;
3559 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003560 deviceId = motionEntry.deviceId;
3561 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003562 } else {
3563 return; // Not a key or a motion
3564 }
3565
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003566 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003567 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003568 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003569 for (const InputTarget& target : targets) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00003570 if (target.dispatchMode == InputTarget::DispatchMode::OUTSIDE) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003571 continue; // Skip windows that receive ACTION_OUTSIDE
3572 }
3573
3574 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003575 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003576 if (connection == nullptr) {
3577 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003578 }
3579 newConnectionTokens.insert(std::move(token));
3580 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003581 if (target.windowHandle) {
3582 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3583 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003584 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003585
3586 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3587 REQUIRES(mLock) {
3588 scoped_unlock unlock(mLock);
3589 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3590 };
3591 postCommandLocked(std::move(command));
3592
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003593 if (newConnectionTokens == mInteractionConnectionTokens) {
3594 return; // no change
3595 }
3596 mInteractionConnectionTokens = newConnectionTokens;
3597
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003598 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003599 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003600 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003601 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003602 std::string message = "Interaction with: " + targetList;
3603 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003604 message += "<none>";
3605 }
3606 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3607}
3608
chaviwfd6d3512019-03-25 13:23:49 -07003609void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003610 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003611 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003612 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3613 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003614 return;
3615 }
3616
Vishnu Nairc519ff72021-01-21 08:23:08 -08003617 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003618 if (focusedToken == token) {
3619 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003620 return;
3621 }
3622
Prabir Pradhancef936d2021-07-21 16:17:52 +00003623 auto command = [this, token]() REQUIRES(mLock) {
3624 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003625 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003626 };
3627 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628}
3629
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003630status_t InputDispatcher::publishMotionEvent(Connection& connection,
3631 DispatchEntry& dispatchEntry) const {
3632 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3633 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3634
3635 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003636 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003637
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003638 // TODO(b/316355518): Do not modify coords before dispatch.
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003639 // Set the X and Y offset and X and Y scale depending on the input source.
3640 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003641 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003642 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3643 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003644 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003645 scaledCoords[i] = motionEntry.pointerCoords[i];
3646 // Don't apply window scale here since we don't want scale to affect raw
3647 // coordinates. The scale will be sent back to the client and applied
3648 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003649 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003650 }
3651 usingCoords = scaledCoords;
3652 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003653 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003654 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003655 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003656 scaledCoords[i].clear();
3657 }
3658 usingCoords = scaledCoords;
3659 }
3660
3661 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3662
3663 // Publish the motion event.
3664 return connection.inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003665 .publishMotionEvent(dispatchEntry.seq, motionEntry.id, motionEntry.deviceId,
3666 motionEntry.source, motionEntry.displayId, std::move(hmac),
3667 motionEntry.action, motionEntry.actionButton,
3668 dispatchEntry.resolvedFlags, motionEntry.edgeFlags,
3669 motionEntry.metaState, motionEntry.buttonState,
3670 motionEntry.classification, dispatchEntry.transform,
3671 motionEntry.xPrecision, motionEntry.yPrecision,
3672 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
3673 dispatchEntry.rawTransform, motionEntry.downTime,
3674 motionEntry.eventTime, motionEntry.getPointerCount(),
3675 motionEntry.pointerProperties.data(), usingCoords);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003676}
3677
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003679 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003680 ATRACE_NAME_IF(ATRACE_ENABLED(),
3681 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3682 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003683 if (DEBUG_DISPATCH_CYCLE) {
3684 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003687 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003688 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003690 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003691 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
3693 // Publish the event.
3694 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003695 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3696 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003697 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003698 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3699 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003700 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003701 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3702 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003705 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003706 status = connection->inputPublisher
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003707 .publishKeyEvent(dispatchEntry->seq, keyEntry.id,
3708 keyEntry.deviceId, keyEntry.source,
3709 keyEntry.displayId, std::move(hmac),
3710 keyEntry.action, dispatchEntry->resolvedFlags,
3711 keyEntry.keyCode, keyEntry.scanCode,
3712 keyEntry.metaState, keyEntry.repeatCount,
3713 keyEntry.downTime, keyEntry.eventTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003714 if (mTracer) {
3715 mTracer->traceEventDispatch(*dispatchEntry, keyEntry.traceTracker.get());
3716 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003720 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003721 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003722 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3723 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003724 }
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003725 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003726 status = publishMotionEvent(*connection, *dispatchEntry);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00003727 if (mTracer) {
3728 mTracer->traceEventDispatch(*dispatchEntry, motionEntry.traceTracker.get());
3729 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003730 break;
3731 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003732
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003733 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003734 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003735 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003736 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003737 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003738 break;
3739 }
3740
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003741 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3742 const TouchModeEntry& touchModeEntry =
3743 static_cast<const TouchModeEntry&>(eventEntry);
3744 status = connection->inputPublisher
3745 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3746 touchModeEntry.inTouchMode);
3747
3748 break;
3749 }
3750
Prabir Pradhan99987712020-11-10 18:43:05 -08003751 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3752 const auto& captureEntry =
3753 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3754 status = connection->inputPublisher
3755 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003756 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003757 break;
3758 }
3759
arthurhungb89ccb02020-12-30 16:19:01 +08003760 case EventEntry::Type::DRAG: {
3761 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3762 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3763 dragEntry.id, dragEntry.x,
3764 dragEntry.y,
3765 dragEntry.isExiting);
3766 break;
3767 }
3768
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003769 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003770 case EventEntry::Type::DEVICE_RESET:
3771 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003772 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003773 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003774 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 }
3777
3778 // Check the result.
3779 if (status) {
3780 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003781 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 "This is unexpected because the wait queue is empty, so the pipe "
3784 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003785 "event to it, status=%s(%d)",
3786 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3787 status);
Harry Cutts33476232023-01-30 19:57:29 +00003788 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 } else {
3790 // Pipe is full and we are waiting for the app to finish process some events
3791 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003792 if (DEBUG_DISPATCH_CYCLE) {
3793 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3794 "waiting for the application to catch up",
3795 connection->getInputChannelName().c_str());
3796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798 } else {
3799 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003800 "status=%s(%d)",
3801 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3802 status);
Harry Cutts33476232023-01-30 19:57:29 +00003803 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805 return;
3806 }
3807
3808 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3810 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3811 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003812 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003813 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003814 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003815 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003816 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
3818}
3819
chaviw09c8d2d2020-08-24 15:48:26 -07003820std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3821 size_t size;
3822 switch (event.type) {
3823 case VerifiedInputEvent::Type::KEY: {
3824 size = sizeof(VerifiedKeyEvent);
3825 break;
3826 }
3827 case VerifiedInputEvent::Type::MOTION: {
3828 size = sizeof(VerifiedMotionEvent);
3829 break;
3830 }
3831 }
3832 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3833 return mHmacKeyManager.sign(start, size);
3834}
3835
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003836const std::array<uint8_t, 32> InputDispatcher::getSignature(
3837 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhan2a2da1d2023-11-03 02:16:20 +00003838 const int32_t actionMasked = MotionEvent::getActionMasked(motionEntry.action);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003839 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003840 // Only sign events up and down events as the purely move events
3841 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003842 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003843 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003844
3845 VerifiedMotionEvent verifiedEvent =
3846 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3847 verifiedEvent.actionMasked = actionMasked;
3848 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3849 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003850}
3851
3852const std::array<uint8_t, 32> InputDispatcher::getSignature(
3853 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3854 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3855 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003856 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003857}
3858
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003860 const std::shared_ptr<Connection>& connection,
3861 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003862 if (DEBUG_DISPATCH_CYCLE) {
3863 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3864 connection->getInputChannelName().c_str(), seq, toString(handled));
3865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00003867 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 return;
3869 }
3870
3871 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003872 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3873 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3874 };
3875 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876}
3877
3878void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003879 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003880 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003881 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003882 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3883 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
3886 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003887 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003888 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003889 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003890 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
3892 // The connection appears to be unrecoverably broken.
3893 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003894 if (connection->status == Connection::Status::NORMAL) {
3895 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
3897 if (notify) {
3898 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003899 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3900 connection->getInputChannelName().c_str());
3901
3902 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003903 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003904 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003905 };
3906 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 }
3908 }
3909}
3910
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003911void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003912 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003913 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003914 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916}
3917
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003918void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003920 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922}
3923
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003924int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3925 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003927 if (connection == nullptr) {
3928 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3929 connectionToken.get(), events);
3930 return 0; // remove the callback
3931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003933 bool notify;
3934 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3935 if (!(events & ALOOPER_EVENT_INPUT)) {
3936 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3937 "events=0x%x",
3938 connection->getInputChannelName().c_str(), events);
3939 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 }
3941
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003942 nsecs_t currentTime = now();
3943 bool gotOne = false;
3944 status_t status = OK;
3945 for (;;) {
3946 Result<InputPublisher::ConsumerResponse> result =
3947 connection->inputPublisher.receiveConsumerResponse();
3948 if (!result.ok()) {
3949 status = result.error().code();
3950 break;
3951 }
3952
3953 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3954 const InputPublisher::Finished& finish =
3955 std::get<InputPublisher::Finished>(*result);
3956 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3957 finish.consumeTime);
3958 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003959 if (shouldReportMetricsForConnection(*connection)) {
3960 const InputPublisher::Timeline& timeline =
3961 std::get<InputPublisher::Timeline>(*result);
3962 mLatencyTracker
3963 .trackGraphicsLatency(timeline.inputEventId,
3964 connection->inputChannel->getConnectionToken(),
3965 std::move(timeline.graphicsTimeline));
3966 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003967 }
3968 gotOne = true;
3969 }
3970 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003971 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003972 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 return 1;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003977 notify = status != DEAD_OBJECT || !connection->monitor;
3978 if (notify) {
3979 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3980 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3981 status);
3982 }
3983 } else {
3984 // Monitor channels are never explicitly unregistered.
3985 // We do it automatically when the remote endpoint is closed so don't warn about them.
3986 const bool stillHaveWindowHandle =
3987 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3988 notify = !connection->monitor && stillHaveWindowHandle;
3989 if (notify) {
3990 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3991 connection->getInputChannelName().c_str(), events);
3992 }
3993 }
3994
3995 // Remove the channel.
3996 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3997 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998}
3999
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004000void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004002 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00004003 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 }
4005}
4006
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004008 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08004009 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004010 for (const Monitor& monitor : monitors) {
4011 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004012 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01004013 }
4014}
4015
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004017 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004018 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004019 if (connection == nullptr) {
4020 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004022
4023 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024}
4025
4026void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004027 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Prabir Pradhanb13da8f2024-01-09 23:10:13 +00004028 if (connection->status != Connection::Status::NORMAL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 return;
4030 }
4031
4032 nsecs_t currentTime = now();
4033
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004034 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07004035 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004037 if (cancelationEvents.empty()) {
4038 return;
4039 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004040
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004041 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
4042 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004043 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004044 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08004045 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004046 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047
Arthur Hungb3307ee2021-10-14 10:57:37 +00004048 std::string reason = std::string("reason=").append(options.reason);
4049 android_log_event_list(LOGTAG_INPUT_CANCEL)
4050 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
4051
hongzuo liu95785e22022-09-06 02:51:35 +00004052 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00004053 // The target to use if we don't find a window associated with the channel.
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004054 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel};
Prabir Pradhan16463382023-10-12 23:03:19 +00004055 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00004056
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004057 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004059 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004060
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004061 switch (cancelationEventEntry->type) {
4062 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004063 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004064 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
4065 ? std::make_optional(keyEntry.displayId)
4066 : std::nullopt;
4067 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004068 addWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4069 /*targetFlags=*/{}, keyEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004070 } else {
4071 targets.emplace_back(fallbackTarget);
4072 }
4073 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004074 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004076 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004077 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00004078 const std::optional<int32_t> targetDisplay =
4079 motionEntry.displayId != ADISPLAY_ID_NONE
4080 ? std::make_optional(motionEntry.displayId)
4081 : std::nullopt;
4082 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004083 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004084 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004085 pointerIndex++) {
4086 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4087 }
Vaibhav Devmurari110ba322023-11-17 10:47:16 +00004088 if (mDragState && mDragState->dragWindow->getToken() == token &&
4089 pointerIds.test(mDragState->pointerId)) {
4090 LOG(INFO) << __func__
4091 << ": Canceling drag and drop because the pointers for the drag "
4092 "window are being canceled.";
4093 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
4094 mDragState.reset();
4095 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004096 addPointerWindowTargetLocked(window, InputTarget::DispatchMode::AS_IS,
4097 ftl::Flags<InputTarget::Flags>(), pointerIds,
4098 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004099 } else {
4100 targets.emplace_back(fallbackTarget);
4101 const auto it = mDisplayInfos.find(motionEntry.displayId);
4102 if (it != mDisplayInfos.end()) {
4103 targets.back().displayTransform = it->second.transform;
4104 targets.back().setDefaultPointerTransform(it->second.transform);
4105 }
4106 }
4107 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004108 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004110 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004111 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004112 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4113 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004114 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004115 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004116 break;
4117 }
4118 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004119 case EventEntry::Type::DEVICE_RESET:
4120 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004121 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004122 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004123 break;
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 }
4126
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004127 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004128 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004130
hongzuo liu95785e22022-09-06 02:51:35 +00004131 // If the outbound queue was previously empty, start the dispatch cycle going.
4132 if (wasEmpty && !connection->outboundQueue.empty()) {
4133 startDispatchCycleLocked(currentTime, connection);
4134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135}
4136
Svet Ganov5d3bc372020-01-26 23:11:07 -08004137void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004138 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004139 ftl::Flags<InputTarget::Flags> targetFlags) {
Prabir Pradhan98ca4a22024-01-09 23:51:50 +00004140 if (connection->status != Connection::Status::NORMAL) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004141 return;
4142 }
4143
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004144 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004145 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004146
4147 if (downEvents.empty()) {
4148 return;
4149 }
4150
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004151 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004152 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4153 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004154 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004155
chaviw98318de2021-05-19 16:45:23 -05004156 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004157 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004158
hongzuo liu95785e22022-09-06 02:51:35 +00004159 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004160 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004161 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004162 switch (downEventEntry->type) {
4163 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004164 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4165 if (windowHandle != nullptr) {
4166 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004167 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004168 pointerIndex++) {
4169 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4170 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004171 addPointerWindowTargetLocked(windowHandle, InputTarget::DispatchMode::AS_IS,
4172 targetFlags, pointerIds, motionEntry.downTime,
4173 targets);
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004174 } else {
4175 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4176 .flags = targetFlags});
4177 const auto it = mDisplayInfos.find(motionEntry.displayId);
4178 if (it != mDisplayInfos.end()) {
4179 targets.back().displayTransform = it->second.transform;
4180 targets.back().setDefaultPointerTransform(it->second.transform);
4181 }
4182 }
4183 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004184 break;
4185 }
4186
4187 case EventEntry::Type::KEY:
4188 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004189 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004190 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004191 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004192 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004193 case EventEntry::Type::SENSOR:
4194 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004195 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004196 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004197 break;
4198 }
4199 }
4200
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004201 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00004202 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0]);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004203 }
4204
hongzuo liu95785e22022-09-06 02:51:35 +00004205 // If the outbound queue was previously empty, start the dispatch cycle going.
4206 if (wasEmpty && !connection->outboundQueue.empty()) {
4207 startDispatchCycleLocked(downTime, connection);
4208 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004209}
4210
Arthur Hungc539dbb2022-12-08 07:45:36 +00004211void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4212 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4213 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004214 std::shared_ptr<Connection> wallpaperConnection =
4215 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004216 if (wallpaperConnection != nullptr) {
4217 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4218 }
4219 }
4220}
4221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004222std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004223 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4224 nsecs_t splitDownTime) {
4225 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
4227 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004228 std::vector<PointerProperties> splitPointerProperties;
4229 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004231 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 uint32_t splitPointerCount = 0;
4233
4234 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004237 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004239 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004241 splitPointerProperties.push_back(pointerProperties);
4242 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 splitPointerCount += 1;
4244 }
4245 }
4246
4247 if (splitPointerCount != pointerIds.count()) {
4248 // This is bad. We are missing some of the pointers that we expected to deliver.
4249 // Most likely this indicates that we received an ACTION_MOVE events that has
4250 // different pointer ids than we expected based on the previous ACTION_DOWN
4251 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4252 // in this way.
4253 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004254 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004255 "a broken sequence of pointer ids from the input device: %s",
4256 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004257 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004260 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4263 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004264 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004266 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004268 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 if (pointerIds.count() == 1) {
4270 // The first/last pointer went down/up.
4271 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004273 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4274 ? AMOTION_EVENT_ACTION_CANCEL
4275 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 } else {
4277 // A secondary pointer went down/up.
4278 uint32_t splitPointerIndex = 0;
4279 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4280 splitPointerIndex += 1;
4281 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 action = maskedAction |
4283 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 }
4285 } else {
4286 // An unrelated pointer changed.
4287 action = AMOTION_EVENT_ACTION_MOVE;
4288 }
4289 }
4290
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004291 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4292 logDispatchStateLocked();
4293 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4294 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4295 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004296 }
4297
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004298 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004299 ATRACE_NAME_IF(ATRACE_ENABLED(),
4300 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4301 ").",
4302 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303 std::unique_ptr<MotionEntry> splitMotionEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004304 std::make_unique<MotionEntry>(newId, originalMotionEntry.injectionState,
4305 originalMotionEntry.eventTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004306 originalMotionEntry.deviceId, originalMotionEntry.source,
4307 originalMotionEntry.displayId,
4308 originalMotionEntry.policyFlags, action,
4309 originalMotionEntry.actionButton,
4310 originalMotionEntry.flags, originalMotionEntry.metaState,
4311 originalMotionEntry.buttonState,
4312 originalMotionEntry.classification,
4313 originalMotionEntry.edgeFlags,
4314 originalMotionEntry.xPrecision,
4315 originalMotionEntry.yPrecision,
4316 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004317 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004318 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 return splitMotionEntry;
4321}
4322
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004323void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4324 std::scoped_lock _l(mLock);
4325 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4326}
4327
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004328void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004329 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004330 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Antonio Kantekf16f2832021-09-28 04:39:20 +00004333 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004337 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004338 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004339 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 } // release lock
4341
4342 if (needWake) {
4343 mLooper->wake();
4344 }
4345}
4346
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004347void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004348 ALOGD_IF(debugInboundEventDetails(),
4349 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4350 ", deviceId=%d, source=%s, displayId=%" PRId32
4351 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4352 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004353 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4354 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4355 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004356 Result<void> keyCheck = validateKeyEvent(args.action);
4357 if (!keyCheck.ok()) {
4358 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 return;
4360 }
4361
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004362 uint32_t policyFlags = args.policyFlags;
4363 int32_t flags = args.flags;
4364 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004365 // InputDispatcher tracks and generates key repeats on behalf of
4366 // whatever notifies it, so repeatCount should always be set to 0
4367 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4369 policyFlags |= POLICY_FLAG_VIRTUAL;
4370 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 if (policyFlags & POLICY_FLAG_FUNCTION) {
4373 metaState |= AMETA_FUNCTION_ON;
4374 }
4375
4376 policyFlags |= POLICY_FLAG_TRUSTED;
4377
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004378 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004380 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4381 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4382 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Michael Wright2b3c3302018-03-02 17:19:13 +00004384 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004385 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004386 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4387 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Antonio Kantekf16f2832021-09-28 04:39:20 +00004391 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 { // acquire lock
4393 mLock.lock();
4394
4395 if (shouldSendKeyToInputFilterLocked(args)) {
4396 mLock.unlock();
4397
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004398 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004399 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 return; // event was consumed by the filter
4401 }
4402
4403 mLock.lock();
4404 }
4405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004406 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004407 std::make_unique<KeyEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4408 args.deviceId, args.source, args.displayId, policyFlags,
4409 args.action, flags, keyCode, args.scanCode, metaState,
4410 repeatCount, args.downTime);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004411 if (mTracer) {
4412 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004415 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 mLock.unlock();
4417 } // release lock
4418
4419 if (needWake) {
4420 mLooper->wake();
4421 }
4422}
4423
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004424bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 return mInputFilterEnabled;
4426}
4427
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004428void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004429 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004430 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004431 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004432 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004433 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4434 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004435 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4436 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4437 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4438 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4439 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004440 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004441 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4442 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004443 i, args.pointerProperties[i].id,
4444 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4445 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4446 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4447 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4448 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4449 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4450 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4451 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4452 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4453 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004456
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004457 Result<void> motionCheck =
4458 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4459 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004460 if (!motionCheck.ok()) {
4461 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4462 return;
4463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004465 if (DEBUG_VERIFY_EVENTS) {
4466 auto [it, _] =
4467 mVerifiersByDisplay.try_emplace(args.displayId,
4468 StringPrintf("display %" PRId32, args.displayId));
4469 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004470 it->second.processMovement(args.deviceId, args.source, args.action,
4471 args.getPointerCount(), args.pointerProperties.data(),
4472 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004473 if (!result.ok()) {
4474 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4475 }
4476 }
4477
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004478 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004480
4481 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004482 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.source, args.action, args.eventTime,
4483 policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004484 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4485 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004486 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
Antonio Kantekf16f2832021-09-28 04:39:20 +00004489 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 { // acquire lock
4491 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004492 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4493 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4494 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004495 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004496 if (touchStateIt != mTouchStatesByDisplay.end()) {
4497 const TouchState& touchState = touchStateIt->second;
Linnan Li907ae732023-09-05 17:14:21 +08004498 if (touchState.hasTouchingPointers(args.deviceId) ||
4499 touchState.hasHoveringPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004500 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4501 }
4502 }
4503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
4505 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004506 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004507 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004508 displayTransform = it->second.transform;
4509 }
4510
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 mLock.unlock();
4512
4513 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004514 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4515 args.action, args.actionButton, args.flags, args.edgeFlags,
4516 args.metaState, args.buttonState, args.classification,
4517 displayTransform, args.xPrecision, args.yPrecision,
4518 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004519 args.downTime, args.eventTime, args.getPointerCount(),
4520 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521
4522 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004523 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 return; // event was consumed by the filter
4525 }
4526
4527 mLock.lock();
4528 }
4529
4530 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004531 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004532 std::make_unique<MotionEntry>(args.id, /*injectionState=*/nullptr, args.eventTime,
4533 args.deviceId, args.source, args.displayId,
4534 policyFlags, args.action, args.actionButton,
4535 args.flags, args.metaState, args.buttonState,
4536 args.classification, args.edgeFlags, args.xPrecision,
4537 args.yPrecision, args.xCursorPosition,
4538 args.yCursorPosition, args.downTime,
4539 args.pointerProperties, args.pointerCoords);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004540 if (mTracer) {
4541 newEntry->traceTracker = mTracer->traceInboundEvent(*newEntry);
4542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004544 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4545 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004546 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004547 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004548 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4549 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4550 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004551 }
4552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004553 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 mLock.unlock();
4555 } // release lock
4556
4557 if (needWake) {
4558 mLooper->wake();
4559 }
4560}
4561
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004562void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004563 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004564 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4565 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004566 args.id, args.eventTime, args.deviceId, args.source,
4567 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004568 }
Chris Yef59a2f42020-10-16 12:55:26 -07004569
Antonio Kantekf16f2832021-09-28 04:39:20 +00004570 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004571 { // acquire lock
4572 mLock.lock();
4573
4574 // Just enqueue a new sensor event.
4575 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004576 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4577 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4578 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004579
4580 needWake = enqueueInboundEventLocked(std::move(newEntry));
4581 mLock.unlock();
4582 } // release lock
4583
4584 if (needWake) {
4585 mLooper->wake();
4586 }
4587}
4588
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004589void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004590 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004591 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4592 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004593 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004594 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004595}
4596
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004597bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004598 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599}
4600
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004601void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004602 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004603 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4604 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004605 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004608 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004610 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611}
4612
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004613void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004614 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004615 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4616 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618
Antonio Kantekf16f2832021-09-28 04:39:20 +00004619 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004621 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004623 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004624 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004625 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004626
4627 for (auto& [_, verifier] : mVerifiersByDisplay) {
4628 verifier.resetDevice(args.deviceId);
4629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 } // release lock
4631
4632 if (needWake) {
4633 mLooper->wake();
4634 }
4635}
4636
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004637void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004638 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004639 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4640 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004641 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004642
Antonio Kantekf16f2832021-09-28 04:39:20 +00004643 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004644 { // acquire lock
4645 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004646 auto entry =
4647 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004648 needWake = enqueueInboundEventLocked(std::move(entry));
4649 } // release lock
4650
4651 if (needWake) {
4652 mLooper->wake();
4653 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004654}
4655
Prabir Pradhan5735a322022-04-11 17:23:34 +00004656InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004657 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004658 InputEventInjectionSync syncMode,
4659 std::chrono::milliseconds timeout,
4660 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004661 Result<void> eventValidation = validateInputEvent(*event);
4662 if (!eventValidation.ok()) {
4663 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4664 return InputEventInjectionResult::FAILED;
4665 }
4666
Prabir Pradhan65613802023-02-22 23:36:58 +00004667 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004668 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4669 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4670 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4671 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004672 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004673 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Prabir Pradhan5735a322022-04-11 17:23:34 +00004675 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004677 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004678 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4679 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4680 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4681 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4682 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004683 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004684 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004685 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004686 }
4687
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004688 const bool isAsync = syncMode == InputEventInjectionSync::NONE;
4689 auto injectionState = std::make_shared<InjectionState>(targetUid, isAsync);
4690
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004691 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004693 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004694 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004695 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004696 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004697 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4698 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4699 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004700 int32_t keyCode = incomingKey.getKeyCode();
4701 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004702 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004703 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004704 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4705 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4706 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4709 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004710 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004711
4712 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4713 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004714 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4716 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4717 std::to_string(t.duration().count()).c_str());
4718 }
4719 }
4720
4721 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004722 std::unique_ptr<KeyEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004723 std::make_unique<KeyEntry>(incomingKey.getId(), injectionState,
4724 incomingKey.getEventTime(), resolvedDeviceId,
4725 incomingKey.getSource(), incomingKey.getDisplayId(),
4726 policyFlags, action, flags, keyCode,
4727 incomingKey.getScanCode(), metaState,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004728 incomingKey.getRepeatCount(),
4729 incomingKey.getDownTime());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004730 if (mTracer) {
4731 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4732 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004733 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 }
4736
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004737 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004738 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004739 const bool isPointerEvent =
4740 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4741 // If a pointer event has no displayId specified, inject it to the default display.
4742 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4743 ? ADISPLAY_ID_DEFAULT
4744 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004745 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746
4747 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004748 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004749 android::base::Timer t;
Yeabkal Wubshit88a90412023-12-21 18:23:04 -08004750 mPolicy.interceptMotionBeforeQueueing(displayId, motionEvent.getSource(),
4751 motionEvent.getAction(), eventTime,
4752 /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4754 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4755 std::to_string(t.duration().count()).c_str());
4756 }
4757 }
4758
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004759 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4760 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4761 }
4762
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004764 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004765 const size_t pointerCount = motionEvent.getPointerCount();
4766 const std::vector<PointerProperties>
4767 pointerProperties(motionEvent.getPointerProperties(),
4768 motionEvent.getPointerProperties() + pointerCount);
4769
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004770 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004771 std::unique_ptr<MotionEntry> injectedEntry =
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004772 std::make_unique<MotionEntry>(motionEvent.getId(), injectionState,
4773 *sampleEventTimes, resolvedDeviceId,
4774 motionEvent.getSource(), displayId, policyFlags,
4775 motionEvent.getAction(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004776 motionEvent.getActionButton(), flags,
4777 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004778 motionEvent.getButtonState(),
4779 motionEvent.getClassification(),
4780 motionEvent.getEdgeFlags(),
4781 motionEvent.getXPrecision(),
4782 motionEvent.getYPrecision(),
4783 motionEvent.getRawXCursorPosition(),
4784 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004785 motionEvent.getDownTime(), pointerProperties,
4786 std::vector<PointerCoords>(samplePointerCoords,
4787 samplePointerCoords +
4788 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004789 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00004790 if (mTracer) {
4791 injectedEntry->traceTracker = mTracer->traceInboundEvent(*injectedEntry);
4792 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004793 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004794 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004796 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004797 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004798 MotionEntry>(motionEvent.getId(), injectionState, *sampleEventTimes,
4799 resolvedDeviceId, motionEvent.getSource(), displayId,
4800 policyFlags, motionEvent.getAction(),
4801 motionEvent.getActionButton(), flags,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004802 motionEvent.getMetaState(), motionEvent.getButtonState(),
4803 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4804 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4805 motionEvent.getRawXCursorPosition(),
4806 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4807 pointerProperties,
4808 std::vector<PointerCoords>(samplePointerCoords,
4809 samplePointerCoords +
4810 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004811 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4812 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004813 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 }
4815 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004819 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 }
4822
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004824 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004825 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004826 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004827 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004828 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004829 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831
4832 mLock.unlock();
4833
4834 if (needWake) {
4835 mLooper->wake();
4836 }
4837
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004838 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004840 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 if (syncMode == InputEventInjectionSync::NONE) {
4843 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 } else {
4845 for (;;) {
4846 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 break;
4849 }
4850
4851 nsecs_t remainingTimeout = endTime - now();
4852 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004853 if (DEBUG_INJECTION) {
4854 ALOGD("injectInputEvent - Timed out waiting for injection result "
4855 "to become available.");
4856 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 break;
4859 }
4860
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004861 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004864 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4865 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004867 if (DEBUG_INJECTION) {
4868 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4869 injectionState->pendingForegroundDispatches);
4870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 nsecs_t remainingTimeout = endTime - now();
4872 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004873 if (DEBUG_INJECTION) {
4874 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4875 "dispatches to finish.");
4876 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004877 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 break;
4879 }
4880
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004881 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 }
4883 }
4884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 } // release lock
4886
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004887 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004888 LOG(INFO) << "injectInputEvent - Finished with result "
4889 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891
4892 return injectionResult;
4893}
4894
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004895std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004896 std::array<uint8_t, 32> calculatedHmac;
4897 std::unique_ptr<VerifiedInputEvent> result;
4898 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004899 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004900 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4901 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4902 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004903 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004904 break;
4905 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004906 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004907 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4908 VerifiedMotionEvent verifiedMotionEvent =
4909 verifiedMotionEventFromMotionEvent(motionEvent);
4910 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004911 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004912 break;
4913 }
4914 default: {
4915 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4916 return nullptr;
4917 }
4918 }
4919 if (calculatedHmac == INVALID_HMAC) {
4920 return nullptr;
4921 }
tyiu1573a672023-02-21 22:38:32 +00004922 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004923 return nullptr;
4924 }
4925 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004926}
4927
Prabir Pradhan24047542023-11-02 17:14:59 +00004928void InputDispatcher::setInjectionResult(const EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004929 InputEventInjectionResult injectionResult) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004930 if (!entry.injectionState) {
4931 // Not an injected event.
4932 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 }
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004934
4935 InjectionState& injectionState = *entry.injectionState;
4936 if (DEBUG_INJECTION) {
4937 LOG(INFO) << "Setting input event injection result to "
4938 << ftl::enum_string(injectionResult);
4939 }
4940
4941 if (injectionState.injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4942 // Log the outcome since the injector did not wait for the injection result.
4943 switch (injectionResult) {
4944 case InputEventInjectionResult::SUCCEEDED:
4945 ALOGV("Asynchronous input event injection succeeded.");
4946 break;
4947 case InputEventInjectionResult::TARGET_MISMATCH:
4948 ALOGV("Asynchronous input event injection target mismatch.");
4949 break;
4950 case InputEventInjectionResult::FAILED:
4951 ALOGW("Asynchronous input event injection failed.");
4952 break;
4953 case InputEventInjectionResult::TIMED_OUT:
4954 ALOGW("Asynchronous input event injection timed out.");
4955 break;
4956 case InputEventInjectionResult::PENDING:
4957 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4958 break;
4959 }
4960 }
4961
4962 injectionState.injectionResult = injectionResult;
4963 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964}
4965
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004966void InputDispatcher::transformMotionEntryForInjectionLocked(
4967 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004968 // Input injection works in the logical display coordinate space, but the input pipeline works
4969 // display space, so we need to transform the injected events accordingly.
4970 const auto it = mDisplayInfos.find(entry.displayId);
4971 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004972 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004973
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004974 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4975 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4976 const vec2 cursor =
4977 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4978 {entry.xCursorPosition, entry.yCursorPosition});
4979 entry.xCursorPosition = cursor.x;
4980 entry.yCursorPosition = cursor.y;
4981 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004982 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004983 entry.pointerCoords[i] =
4984 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4985 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004986 }
4987}
4988
Prabir Pradhan24047542023-11-02 17:14:59 +00004989void InputDispatcher::incrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004990 if (entry.injectionState) {
4991 entry.injectionState->pendingForegroundDispatches += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 }
4993}
4994
Prabir Pradhan24047542023-11-02 17:14:59 +00004995void InputDispatcher::decrementPendingForegroundDispatches(const EventEntry& entry) {
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004996 if (entry.injectionState) {
4997 entry.injectionState->pendingForegroundDispatches -= 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
Prabir Pradhana8cdbe12023-11-01 21:30:02 +00004999 if (entry.injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005000 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 }
5002 }
5003}
5004
chaviw98318de2021-05-19 16:45:23 -05005005const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005006 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05005007 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07005008 auto it = mWindowHandlesByDisplay.find(displayId);
5009 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08005010}
5011
chaviw98318de2021-05-19 16:45:23 -05005012sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00005013 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08005014 if (windowHandleToken == nullptr) {
5015 return nullptr;
5016 }
5017
Prabir Pradhan16463382023-10-12 23:03:19 +00005018 if (!displayId) {
5019 // Look through all displays.
5020 for (auto& it : mWindowHandlesByDisplay) {
5021 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5022 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
5023 if (windowHandle->getToken() == windowHandleToken) {
5024 return windowHandle;
5025 }
Arthur Hungb92218b2018-08-14 12:00:21 +08005026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005028 return nullptr;
5029 }
5030
Prabir Pradhan16463382023-10-12 23:03:19 +00005031 // Only look through the requested display.
5032 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005033 if (windowHandle->getToken() == windowHandleToken) {
5034 return windowHandle;
5035 }
5036 }
5037 return nullptr;
5038}
5039
chaviw98318de2021-05-19 16:45:23 -05005040sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
5041 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00005042 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005043 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
5044 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08005045 if (handle->getId() == windowHandle->getId() &&
5046 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00005047 if (windowHandle->getInfo()->displayId != it.first) {
5048 ALOGE("Found window %s in display %" PRId32
5049 ", but it should belong to display %" PRId32,
5050 windowHandle->getName().c_str(), it.first,
5051 windowHandle->getInfo()->displayId);
5052 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005053 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08005054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 }
5056 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005057 return nullptr;
5058}
5059
chaviw98318de2021-05-19 16:45:23 -05005060sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005061 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
5062 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063}
5064
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00005065ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
5066 auto displayInfoIt = mDisplayInfos.find(displayId);
5067 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
5068 : kIdentityTransform;
5069}
5070
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005071bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
5072 const MotionEntry& motionEntry) const {
5073 const WindowInfo& info = *window->getInfo();
5074
5075 // Skip spy window targets that are not valid for targeted injection.
5076 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005077 return false;
5078 }
5079
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005080 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
5081 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
5082 return false;
5083 }
5084
5085 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
5086 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
5087 window->getName().c_str());
5088 return false;
5089 }
5090
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005091 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005092 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005093 ALOGW("Not sending touch to %s because there's no corresponding connection",
5094 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005095 return false;
5096 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005097
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005098 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005099 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005100 return false;
5101 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005102
5103 // Drop events that can't be trusted due to occlusion
5104 const auto [x, y] = resolveTouchedPosition(motionEntry);
5105 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
5106 if (!isTouchTrustedLocked(occlusionInfo)) {
5107 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00005108 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005109 for (const auto& log : occlusionInfo.debugInfo) {
5110 ALOGD("%s", log.c_str());
5111 }
5112 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005113 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5114 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005115 return false;
5116 }
5117
5118 // Drop touch events if requested by input feature
5119 if (shouldDropInput(motionEntry, window)) {
5120 return false;
5121 }
5122
Siarhei Vishniakouf77f60a2023-10-23 17:26:05 -07005123 // Ignore touches if stylus is down anywhere on screen
5124 if (info.inputConfig.test(WindowInfo::InputConfig::GLOBAL_STYLUS_BLOCKS_TOUCH) &&
5125 isStylusActiveInDisplay(info.displayId, mTouchStatesByDisplay)) {
5126 LOG(INFO) << "Dropping touch from " << window->getName() << " because stylus is active";
5127 return false;
5128 }
5129
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 return true;
5131}
5132
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005133std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5134 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005135 auto connectionIt = mConnectionsByToken.find(token);
5136 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005137 return nullptr;
5138 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005140}
5141
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005142void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005143 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5144 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005145 // Remove all handles on a display if there are no windows left.
5146 mWindowHandlesByDisplay.erase(displayId);
5147 return;
5148 }
5149
5150 // Since we compare the pointer of input window handles across window updates, we need
5151 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005152 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5153 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5154 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005155 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005156 }
5157
chaviw98318de2021-05-19 16:45:23 -05005158 std::vector<sp<WindowInfoHandle>> newHandles;
5159 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005160 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005161 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005162 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005163 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005164 const bool canReceiveInput =
5165 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5166 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005167 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005168 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005169 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005170 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005171 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005172 }
5173
5174 if (info->displayId != displayId) {
5175 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5176 handle->getName().c_str(), displayId, info->displayId);
5177 continue;
5178 }
5179
Robert Carredd13602020-04-13 17:24:34 -07005180 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5181 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005182 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005183 oldHandle->updateFrom(handle);
5184 newHandles.push_back(oldHandle);
5185 } else {
5186 newHandles.push_back(handle);
5187 }
5188 }
5189
5190 // Insert or replace
5191 mWindowHandlesByDisplay[displayId] = newHandles;
5192}
5193
Arthur Hungb92218b2018-08-14 12:00:21 +08005194/**
5195 * Called from InputManagerService, update window handle list by displayId that can receive input.
5196 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5197 * If set an empty list, remove all handles from the specific display.
5198 * For focused handle, check if need to change and send a cancel event to previous one.
5199 * For removed handle, check if need to send a cancel event if already in touch.
5200 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005201void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005202 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005203 if (DEBUG_FOCUS) {
5204 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005205 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005206 windowList += iwh->getName() + " ";
5207 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005208 LOG(INFO) << "setInputWindows displayId=" << displayId << " " << windowList;
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210
Prabir Pradhand65552b2021-10-07 11:23:50 -07005211 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005212 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005213 const WindowInfo& info = *window->getInfo();
5214
5215 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005216 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005217 if (noInputWindow && window->getToken() != nullptr) {
5218 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5219 window->getName().c_str());
5220 window->releaseChannel();
5221 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005222
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005223 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005224 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5225 !info.inputConfig.test(
5226 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005227 "%s has feature SPY, but is not a trusted overlay.",
5228 window->getName().c_str());
5229
Prabir Pradhand65552b2021-10-07 11:23:50 -07005230 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005231 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5232 !info.inputConfig.test(
5233 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005234 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5235 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005236 }
5237
Arthur Hung72d8dc32020-03-28 00:48:39 +00005238 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005239 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240
chaviw98318de2021-05-19 16:45:23 -05005241 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005242
chaviw98318de2021-05-19 16:45:23 -05005243 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005244
Vishnu Nairc519ff72021-01-21 08:23:08 -08005245 std::optional<FocusResolver::FocusChanges> changes =
5246 mFocusResolver.setInputWindows(displayId, windowHandles);
5247 if (changes) {
5248 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005251 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5252 mTouchStatesByDisplay.find(displayId);
5253 if (stateIt != mTouchStatesByDisplay.end()) {
5254 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005255 for (size_t i = 0; i < state.windows.size();) {
5256 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005257 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07005258 LOG(INFO) << "Touched window was removed: " << touchedWindow.windowHandle->getName()
5259 << " in display %" << displayId;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005260 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005261 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5262 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005263 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005264 "touched window was removed");
5265 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005266 // Since we are about to drop the touch, cancel the events for the wallpaper as
5267 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005268 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005269 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5270 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005271 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005272 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005275 state.windows.erase(state.windows.begin() + i);
5276 } else {
5277 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 }
5279 }
arthurhungb89ccb02020-12-30 16:19:01 +08005280
arthurhung6d4bed92021-03-17 11:59:33 +08005281 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005282 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005283 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005284 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005285 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005286 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5287 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005288 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005289 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005290 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005291
Arthur Hung72d8dc32020-03-28 00:48:39 +00005292 // Release information for windows that are no longer present.
5293 // This ensures that unused input channels are released promptly.
5294 // Otherwise, they might stick around until the window handle is destroyed
5295 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005296 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005297 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005298 if (DEBUG_FOCUS) {
5299 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005300 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005301 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005302 }
chaviw291d88a2019-02-14 10:33:58 -08005303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304}
5305
5306void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005307 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005308 if (DEBUG_FOCUS) {
5309 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5310 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5311 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005312 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005313 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005314 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 } // release lock
5316
5317 // Wake up poll loop since it may need to make new input dispatching choices.
5318 mLooper->wake();
5319}
5320
Vishnu Nair599f1412021-06-21 10:39:58 -07005321void InputDispatcher::setFocusedApplicationLocked(
5322 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5323 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5324 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5325
5326 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5327 return; // This application is already focused. No need to wake up or change anything.
5328 }
5329
5330 // Set the new application handle.
5331 if (inputApplicationHandle != nullptr) {
5332 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5333 } else {
5334 mFocusedApplicationHandlesByDisplay.erase(displayId);
5335 }
5336
5337 // No matter what the old focused application was, stop waiting on it because it is
5338 // no longer focused.
5339 resetNoFocusedWindowTimeoutLocked();
5340}
5341
Yeabkal Wubshitb8aadfa2024-01-17 17:03:42 -08005342void InputDispatcher::setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) {
5343 if (interval.count() < 0) {
5344 LOG_ALWAYS_FATAL("Minimum time between user activity pokes should be >= 0");
5345 }
5346 std::scoped_lock _l(mLock);
5347 mMinTimeBetweenUserActivityPokes = interval;
5348}
5349
Tiger Huang721e26f2018-07-24 22:26:19 +08005350/**
5351 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5352 * the display not specified.
5353 *
5354 * We track any unreleased events for each window. If a window loses the ability to receive the
5355 * released event, we will send a cancel event to it. So when the focused display is changed, we
5356 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5357 * display. The display-specified events won't be affected.
5358 */
5359void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005360 if (DEBUG_FOCUS) {
5361 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5362 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005363 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005364 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005365
5366 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005367 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005368 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005369 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005370 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005371 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005372 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005373 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005374 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005375 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005376 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005377 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5378 }
5379 }
5380 mFocusedDisplayId = displayId;
5381
Chris Ye3c2d6f52020-08-09 10:39:48 -07005382 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005383 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005384 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005385
Vishnu Nairad321cd2020-08-20 16:40:21 -07005386 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005388 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005389 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005390 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005391 }
5392 }
5393 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005394 } // release lock
5395
5396 // Wake up poll loop since it may need to make new input dispatching choices.
5397 mLooper->wake();
5398}
5399
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005401 if (DEBUG_FOCUS) {
5402 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404
5405 bool changed;
5406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005407 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
5409 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5410 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005411 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 }
5413
5414 if (mDispatchEnabled && !enabled) {
5415 resetAndDropEverythingLocked("dispatcher is being disabled");
5416 }
5417
5418 mDispatchEnabled = enabled;
5419 mDispatchFrozen = frozen;
5420 changed = true;
5421 } else {
5422 changed = false;
5423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 } // release lock
5425
5426 if (changed) {
5427 // Wake up poll loop since it may need to make new input dispatching choices.
5428 mLooper->wake();
5429 }
5430}
5431
5432void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005433 if (DEBUG_FOCUS) {
5434 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436
5437 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005438 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439
5440 if (mInputFilterEnabled == enabled) {
5441 return;
5442 }
5443
5444 mInputFilterEnabled = enabled;
5445 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5446 } // release lock
5447
5448 // Wake up poll loop since there might be work to do to drop everything.
5449 mLooper->wake();
5450}
5451
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005452bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005453 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005454 bool needWake = false;
5455 {
5456 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005457 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005458 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005459 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005460 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5461 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005462 mTouchModePerDisplay.count(displayId) == 0
5463 ? "not set"
5464 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5465
Antonio Kantek15beb512022-06-13 22:35:41 +00005466 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5467 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005468 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005469 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005470 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005471 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5472 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005473 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005474 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005475 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005476 return false;
5477 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005478 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005479 mTouchModePerDisplay[displayId] = inTouchMode;
5480 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5481 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005482 needWake = enqueueInboundEventLocked(std::move(entry));
5483 } // release lock
5484
5485 if (needWake) {
5486 mLooper->wake();
5487 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005488 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005489}
5490
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005491bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005492 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5493 if (focusedToken == nullptr) {
5494 return false;
5495 }
5496 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5497 return isWindowOwnedBy(windowHandle, pid, uid);
5498}
5499
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005500bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005501 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5502 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5503 const sp<WindowInfoHandle> windowHandle =
5504 getWindowHandleLocked(connectionToken);
5505 return isWindowOwnedBy(windowHandle, pid, uid);
5506 }) != mInteractionConnectionTokens.end();
5507}
5508
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005509void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5510 if (opacity < 0 || opacity > 1) {
5511 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5512 return;
5513 }
5514
5515 std::scoped_lock lock(mLock);
5516 mMaximumObscuringOpacityForTouch = opacity;
5517}
5518
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005519std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5520InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005521 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5522 for (TouchedWindow& w : state.windows) {
5523 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005524 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005525 }
5526 }
5527 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005528 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005529}
5530
arthurhungb89ccb02020-12-30 16:19:01 +08005531bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5532 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005533 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005534 if (DEBUG_FOCUS) {
5535 ALOGD("Trivial transfer to same window.");
5536 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005537 return true;
5538 }
5539
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005541 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
Arthur Hungabbb9d82021-09-01 14:52:30 +00005543 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005544 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005545
Arthur Hungabbb9d82021-09-01 14:52:30 +00005546 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005547 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 return false;
5549 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005550 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5551 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005552 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5553 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005554 return false;
5555 }
5556 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005557
Arthur Hungabbb9d82021-09-01 14:52:30 +00005558 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5559 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005560 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005561 return false;
5562 }
5563
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005564 if (DEBUG_FOCUS) {
5565 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005566 touchedWindow->windowHandle->getName().c_str(),
5567 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 }
5569
Arthur Hungabbb9d82021-09-01 14:52:30 +00005570 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005571 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005572 std::vector<PointerProperties> pointers = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005573 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005574 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575
Arthur Hungabbb9d82021-09-01 14:52:30 +00005576 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005577 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005578 ftl::Flags<InputTarget::Flags> newTargetFlags =
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005579 oldTargetFlags & (InputTarget::Flags::SPLIT);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005580 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005581 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005582 }
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00005583 state->addOrUpdateWindow(toWindowHandle, InputTarget::DispatchMode::AS_IS, newTargetFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005584 deviceId, pointers, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585
Arthur Hungabbb9d82021-09-01 14:52:30 +00005586 // Store the dragging window.
5587 if (isDragDrop) {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005588 if (pointers.size() != 1) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005589 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5590 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005591 return false;
5592 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005593 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005594 const size_t id = pointers.begin()->id;
Arthur Hung54745652022-04-20 07:17:41 +00005595 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 }
5597
Arthur Hungabbb9d82021-09-01 14:52:30 +00005598 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005599 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5600 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005601 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005602 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005603 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5604 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005606 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5607 newTargetFlags);
5608
5609 // Check if the wallpaper window should deliver the corresponding event.
5610 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08005611 *state, deviceId, pointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 } // release lock
5614
5615 // Wake up poll loop since it may need to make new input dispatching choices.
5616 mLooper->wake();
5617 return true;
5618}
5619
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005620/**
5621 * Get the touched foreground window on the given display.
5622 * Return null if there are no windows touched on that display, or if more than one foreground
5623 * window is being touched.
5624 */
5625sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5626 auto stateIt = mTouchStatesByDisplay.find(displayId);
5627 if (stateIt == mTouchStatesByDisplay.end()) {
5628 ALOGI("No touch state on display %" PRId32, displayId);
5629 return nullptr;
5630 }
5631
5632 const TouchState& state = stateIt->second;
5633 sp<WindowInfoHandle> touchedForegroundWindow;
5634 // If multiple foreground windows are touched, return nullptr
5635 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005636 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005637 if (touchedForegroundWindow != nullptr) {
5638 ALOGI("Two or more foreground windows: %s and %s",
5639 touchedForegroundWindow->getName().c_str(),
5640 window.windowHandle->getName().c_str());
5641 return nullptr;
5642 }
5643 touchedForegroundWindow = window.windowHandle;
5644 }
5645 }
5646 return touchedForegroundWindow;
5647}
5648
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005649// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005650bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005651 sp<IBinder> fromToken;
5652 { // acquire lock
5653 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005654 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005655 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005656 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5657 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005658 return false;
5659 }
5660
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005661 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5662 if (from == nullptr) {
5663 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5664 return false;
5665 }
5666
5667 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005668 } // release lock
5669
5670 return transferTouchFocus(fromToken, destChannelToken);
5671}
5672
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005674 if (DEBUG_FOCUS) {
5675 ALOGD("Resetting and dropping all events (%s).", reason);
5676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677
Michael Wrightfb04fd52022-11-24 22:31:11 +00005678 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 synthesizeCancelationEventsForAllConnectionsLocked(options);
5680
5681 resetKeyRepeatLocked();
5682 releasePendingEventLocked();
5683 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005684 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005686 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005687 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688}
5689
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005690void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005691 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 dumpDispatchStateLocked(dump);
5693
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005694 std::istringstream stream(dump);
5695 std::string line;
5696
5697 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005698 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 }
5700}
5701
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005702std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005703 std::string dump;
5704
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005705 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5706 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005707
5708 std::string windowName = "None";
5709 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005710 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005711 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5712 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5713 : "token has capture without window";
5714 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005715 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005716
5717 return dump;
5718}
5719
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005720void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005721 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5722 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5723 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005724 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725
Tiger Huang721e26f2018-07-24 22:26:19 +08005726 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5727 dump += StringPrintf(INDENT "FocusedApplications:\n");
5728 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5729 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005730 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005731 const std::chrono::duration timeout =
5732 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005733 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005734 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005735 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005738 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005740
Vishnu Nairc519ff72021-01-21 08:23:08 -08005741 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005742 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005744 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005745 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005746 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005747 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5748 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
5750 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005751 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 }
5753
arthurhung6d4bed92021-03-17 11:59:33 +08005754 if (mDragState) {
5755 dump += StringPrintf(INDENT "DragState:\n");
5756 mDragState->dump(dump, INDENT2);
5757 }
5758
Arthur Hungb92218b2018-08-14 12:00:21 +08005759 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005760 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5761 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5762 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5763 const auto& displayInfo = it->second;
5764 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5765 displayInfo.logicalHeight);
5766 displayInfo.transform.dump(dump, "transform", INDENT4);
5767 } else {
5768 dump += INDENT2 "No DisplayInfo found!\n";
5769 }
5770
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005771 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005772 dump += INDENT2 "Windows:\n";
5773 for (size_t i = 0; i < windowHandles.size(); i++) {
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005774 dump += StringPrintf(INDENT3 "%zu: %s", i,
5775 streamableToString(*windowHandles[i]).c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08005776 }
5777 } else {
5778 dump += INDENT2 "Windows: <none>\n";
5779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005782 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005785 if (!mGlobalMonitorsByDisplay.empty()) {
5786 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5787 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005788 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005791 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005794 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795
5796 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005797 if (!mRecentQueue.empty()) {
5798 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005799 for (const std::shared_ptr<const EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005800 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005801 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005802 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 }
5804 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005805 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806 }
5807
5808 // Dump event currently being dispatched.
5809 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005810 dump += INDENT "PendingEvent:\n";
5811 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005812 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005813 dump += StringPrintf(", age=%" PRId64 "ms\n",
5814 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005816 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818
5819 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005820 if (!mInboundQueue.empty()) {
5821 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Prabir Pradhan24047542023-11-02 17:14:59 +00005822 for (const std::shared_ptr<const EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005823 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005824 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005825 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 }
5827 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005828 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 }
5830
Prabir Pradhancef936d2021-07-21 16:17:52 +00005831 if (!mCommandQueue.empty()) {
5832 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5833 } else {
5834 dump += INDENT "CommandQueue: <empty>\n";
5835 }
5836
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005837 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005838 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005839 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005840 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005841 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005842 connection->inputChannel->getFd().get(),
5843 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005844 connection->getWindowName().c_str(),
5845 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005848 if (!connection->outboundQueue.empty()) {
5849 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5850 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005851 dump += dumpQueue(connection->outboundQueue, currentTime);
5852
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005854 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 }
5856
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005857 if (!connection->waitQueue.empty()) {
5858 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5859 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005860 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005862 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 }
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005864 std::string inputStateDump = streamableToString(connection->inputState);
5865 if (!inputStateDump.empty()) {
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005866 dump += INDENT3 "InputState: ";
Siarhei Vishniakou366fb5b2023-12-06 11:23:41 -08005867 dump += inputStateDump + "\n";
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 }
5870 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005871 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 }
5873
Antonio Kantek15beb512022-06-13 22:35:41 +00005874 if (!mTouchModePerDisplay.empty()) {
5875 dump += INDENT "TouchModePerDisplay:\n";
5876 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5877 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5878 std::to_string(touchMode).c_str());
5879 }
5880 } else {
5881 dump += INDENT "TouchModePerDisplay: <none>\n";
5882 }
5883
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005884 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005885 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5886 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5887 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005888 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005889 dump += mLatencyAggregator.dump(INDENT2);
Prabir Pradhanabcdf5c2023-12-15 07:30:22 +00005890 dump += INDENT "InputTracer: ";
5891 dump += mTracer == nullptr ? "Disabled" : "Enabled";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892}
5893
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005894void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005895 const size_t numMonitors = monitors.size();
5896 for (size_t i = 0; i < numMonitors; i++) {
5897 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005898 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005899 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5900 dump += "\n";
5901 }
5902}
5903
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005904class LooperEventCallback : public LooperCallback {
5905public:
5906 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5907 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5908
5909private:
5910 std::function<int(int events)> mCallback;
5911};
5912
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005913Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005914 if (DEBUG_CHANNEL_CREATION) {
5915 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005918 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005919 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005920 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005921
5922 if (result) {
5923 return base::Error(result) << "Failed to open input channel pair with name " << name;
5924 }
5925
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005927 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005928 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005929 auto&& fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005930 std::shared_ptr<Connection> connection =
5931 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5932 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005934 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5935 ALOGE("Created a new connection, but the token %p is already known", token.get());
5936 }
5937 mConnectionsByToken.emplace(token, connection);
5938
5939 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5940 this, std::placeholders::_1, token);
5941
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005942 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005943 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 } // release lock
5945
5946 // Wake the looper because some connections have changed.
5947 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005948 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949}
5950
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005951Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005952 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005953 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005954 std::shared_ptr<InputChannel> serverChannel;
5955 std::unique_ptr<InputChannel> clientChannel;
5956 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5957 if (result) {
5958 return base::Error(result) << "Failed to open input channel pair with name " << name;
5959 }
5960
Michael Wright3dd60e22019-03-27 22:06:44 +00005961 { // acquire lock
5962 std::scoped_lock _l(mLock);
5963
5964 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005965 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5966 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005967 }
5968
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005969 std::shared_ptr<Connection> connection =
5970 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005971 const sp<IBinder>& token = serverChannel->getConnectionToken();
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005972 auto&& fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005973
5974 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5975 ALOGE("Created a new connection, but the token %p is already known", token.get());
5976 }
5977 mConnectionsByToken.emplace(token, connection);
5978 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5979 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005980
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005981 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005982
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08005983 mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005984 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005985 }
Garfield Tan15601662020-09-22 15:32:38 -07005986
Michael Wright3dd60e22019-03-27 22:06:44 +00005987 // Wake the looper because some connections have changed.
5988 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005989 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005990}
5991
Garfield Tan15601662020-09-22 15:32:38 -07005992status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005993 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005994 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995
Harry Cutts33476232023-01-30 19:57:29 +00005996 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 if (status) {
5998 return status;
5999 }
6000 } // release lock
6001
6002 // Wake the poll loop because removing the connection may have changed the current
6003 // synchronization state.
6004 mLooper->wake();
6005 return OK;
6006}
6007
Garfield Tan15601662020-09-22 15:32:38 -07006008status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
6009 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006010 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006011 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00006012 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013 return BAD_VALUE;
6014 }
6015
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006016 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07006017
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006019 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 }
6021
Tomasz Wasilczyk32024602023-11-16 10:17:54 -08006022 mLooper->removeFd(connection->inputChannel->getFd().get());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023
6024 nsecs_t currentTime = now();
6025 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
6026
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006027 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 return OK;
6029}
6030
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05006031void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006032 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
6033 auto& [displayId, monitors] = *it;
6034 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
6035 return monitor.inputChannel->getConnectionToken() == connectionToken;
6036 });
Michael Wright3dd60e22019-03-27 22:06:44 +00006037
Michael Wright3dd60e22019-03-27 22:06:44 +00006038 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006039 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08006040 } else {
6041 ++it;
6042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043 }
6044}
6045
Michael Wright3dd60e22019-03-27 22:06:44 +00006046status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006047 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006048 return pilferPointersLocked(token);
6049}
Michael Wright3dd60e22019-03-27 22:06:44 +00006050
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006051status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006052 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
6053 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006054 LOG(WARNING)
6055 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006056 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00006057 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006058
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07006059 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006060 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006061 LOG(WARNING)
6062 << "Attempted to pilfer points from a channel without any on-going pointer streams."
6063 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006064 return BAD_VALUE;
6065 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006066 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
Siarhei Vishniakou2899c552023-07-10 18:20:46 -07006067 if (deviceIds.empty()) {
6068 LOG(WARNING) << "Can't pilfer: no touching devices in window: " << windowPtr->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006069 return BAD_VALUE;
6070 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006071
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006072 for (const DeviceId deviceId : deviceIds) {
6073 TouchState& state = *statePtr;
6074 TouchedWindow& window = *windowPtr;
6075 // Send cancel events to all the input channels we're stealing from.
6076 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6077 "input channel stole pointer stream");
6078 options.deviceId = deviceId;
6079 options.displayId = displayId;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006080 std::vector<PointerProperties> pointers = window.getTouchingPointers(deviceId);
6081 std::bitset<MAX_POINTER_ID + 1> pointerIds = getPointerIds(pointers);
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006082 options.pointerIds = pointerIds;
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006083
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006084 std::string canceledWindows;
6085 for (const TouchedWindow& w : state.windows) {
6086 const std::shared_ptr<InputChannel> channel =
6087 getInputChannelLocked(w.windowHandle->getToken());
6088 if (channel != nullptr && channel->getConnectionToken() != token) {
6089 synthesizeCancelationEventsForInputChannelLocked(channel, options);
6090 canceledWindows += canceledWindows.empty() ? "[" : ", ";
6091 canceledWindows += channel->getName();
6092 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006093 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006094 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6095 LOG(INFO) << "Channel " << requestingChannel->getName()
6096 << " is stealing input gesture for device " << deviceId << " from "
6097 << canceledWindows;
6098
6099 // Prevent the gesture from being sent to any other windows.
6100 // This only blocks relevant pointers to be sent to other windows
6101 window.addPilferingPointers(deviceId, pointerIds);
6102
6103 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006104 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006105 return OK;
6106}
6107
Prabir Pradhan99987712020-11-10 18:43:05 -08006108void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6109 { // acquire lock
6110 std::scoped_lock _l(mLock);
6111 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006112 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006113 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6114 windowHandle != nullptr ? windowHandle->getName().c_str()
6115 : "token without window");
6116 }
6117
Vishnu Nairc519ff72021-01-21 08:23:08 -08006118 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006119 if (focusedToken != windowToken) {
6120 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6121 enabled ? "enable" : "disable");
6122 return;
6123 }
6124
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006125 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006126 ALOGW("Ignoring request to %s Pointer Capture: "
6127 "window has %s requested pointer capture.",
6128 enabled ? "enable" : "disable", enabled ? "already" : "not");
6129 return;
6130 }
6131
Christine Franksb768bb42021-11-29 12:11:31 -08006132 if (enabled) {
6133 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6134 mIneligibleDisplaysForPointerCapture.end(),
6135 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6136 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6137 return;
6138 }
6139 }
6140
Prabir Pradhan99987712020-11-10 18:43:05 -08006141 setPointerCaptureLocked(enabled);
6142 } // release lock
6143
6144 // Wake the thread to process command entries.
6145 mLooper->wake();
6146}
6147
Christine Franksb768bb42021-11-29 12:11:31 -08006148void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6149 { // acquire lock
6150 std::scoped_lock _l(mLock);
6151 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6152 if (!isEligible) {
6153 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6154 }
6155 } // release lock
6156}
6157
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006158std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006159 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006160 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006161 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006162 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006163 }
6164 }
6165 }
6166 return std::nullopt;
6167}
6168
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006169std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6170 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006171 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006172 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006173 }
6174
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006175 for (const auto& [token, connection] : mConnectionsByToken) {
6176 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006177 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178 }
6179 }
Robert Carr4e670e52018-08-15 13:26:12 -07006180
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006181 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182}
6183
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006184std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006185 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006186 if (connection == nullptr) {
6187 return "<nullptr>";
6188 }
6189 return connection->getInputChannelName();
6190}
6191
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006192void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006193 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006194 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006195}
6196
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006198 const std::shared_ptr<Connection>& connection,
6199 uint32_t seq, bool handled,
6200 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006201 // Handle post-event policy actions.
Prabir Pradhan24047542023-11-02 17:14:59 +00006202 std::unique_ptr<const KeyEntry> fallbackKeyEntry;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006203
6204 { // Start critical section
6205 auto dispatchEntryIt =
6206 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6207 [seq](auto& e) { return e->seq == seq; });
6208 if (dispatchEntryIt == connection->waitQueue.end()) {
6209 return;
6210 }
6211
6212 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6213
6214 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6215 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6216 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6217 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6218 }
6219 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6220 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6221 connection->inputChannel->getConnectionToken(),
6222 dispatchEntry.deliveryTime, consumeTime, finishTime);
6223 }
6224
6225 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006226 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*(dispatchEntry.eventEntry));
6227 fallbackKeyEntry =
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006228 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006229 }
6230 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231
6232 // Dequeue the event and start the next cycle.
6233 // Because the lock might have been released, it is possible that the
6234 // contents of the wait queue to have been drained, so we need to double-check
6235 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006236 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6237 [seq](auto& e) { return e->seq == seq; });
6238 if (entryIt != connection->waitQueue.end()) {
6239 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6240 connection->waitQueue.erase(entryIt);
6241
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6243 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6244 if (!connection->responsive) {
6245 connection->responsive = isConnectionResponsive(*connection);
6246 if (connection->responsive) {
6247 // The connection was unresponsive, and now it's responsive.
6248 processConnectionResponsiveLocked(*connection);
6249 }
6250 }
6251 traceWaitQueueLength(*connection);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006252 if (fallbackKeyEntry && connection->status == Connection::Status::NORMAL) {
6253 const InputTarget target{.inputChannel = connection->inputChannel,
6254 .flags = dispatchEntry->targetFlags};
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006255 enqueueDispatchEntryLocked(connection, std::move(fallbackKeyEntry), target);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006257 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 }
6259
6260 // Start the next dispatch cycle for this connection.
6261 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262}
6263
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6265 const sp<IBinder>& newToken) {
6266 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6267 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006268 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006269 };
6270 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271}
6272
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6274 auto command = [this, token, x, y]() REQUIRES(mLock) {
6275 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006276 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006277 };
6278 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006279}
6280
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006281void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006282 if (connection == nullptr) {
6283 LOG_ALWAYS_FATAL("Caller must check for nullness");
6284 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006285 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6286 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006287 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006288 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006289 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006290 return;
6291 }
6292 /**
6293 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6294 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6295 * has changed. This could cause newer entries to time out before the already dispatched
6296 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6297 * processes the events linearly. So providing information about the oldest entry seems to be
6298 * most useful.
6299 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006300 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6301 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006302 std::string reason =
6303 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006304 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006305 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006306 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006307 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006308 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006309
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006310 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6311
6312 // Stop waking up for events on this connection, it is already unresponsive
6313 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006314}
6315
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006316void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6317 std::string reason =
6318 StringPrintf("%s does not have a focused window", application->getName().c_str());
6319 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006320
Yabin Cui8eb9c552023-06-08 18:05:07 +00006321 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006322 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006323 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006324 };
6325 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006326}
6327
chaviw98318de2021-05-19 16:45:23 -05006328void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006329 const std::string& reason) {
6330 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6331 updateLastAnrStateLocked(windowLabel, reason);
6332}
6333
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006334void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6335 const std::string& reason) {
6336 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006337 updateLastAnrStateLocked(windowLabel, reason);
6338}
6339
6340void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6341 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006343 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 struct tm tm;
6345 localtime_r(&t, &tm);
6346 char timestr[64];
6347 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006348 mLastAnrState.clear();
6349 mLastAnrState += INDENT "ANR:\n";
6350 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006351 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6352 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006353 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354}
6355
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
Prabir Pradhan24047542023-11-02 17:14:59 +00006357 const KeyEntry& entry) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006358 const KeyEvent event = createKeyEvent(entry);
6359 nsecs_t delay = 0;
6360 { // release lock
6361 scoped_unlock unlock(mLock);
6362 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006363 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006364 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6365 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6366 std::to_string(t.duration().count()).c_str());
6367 }
6368 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369
6370 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006371 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006372 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006373 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006375 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006376 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378}
6379
Prabir Pradhancef936d2021-07-21 16:17:52 +00006380void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006381 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006382 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006383 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006384 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006385 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006386 };
6387 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006388}
6389
Prabir Pradhanedd96402022-02-15 01:46:16 -08006390void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006391 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006392 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006393 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006394 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006395 };
6396 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006397}
6398
6399/**
6400 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6401 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6402 * command entry to the command queue.
6403 */
6404void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6405 std::string reason) {
6406 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006407 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006408 if (connection.monitor) {
6409 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6410 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006411 pid = findMonitorPidByTokenLocked(connectionToken);
6412 } else {
6413 // The connection is a window
6414 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6415 reason.c_str());
6416 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6417 if (handle != nullptr) {
6418 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006419 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006420 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006421 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006422}
6423
6424/**
6425 * Tell the policy that a connection has become responsive so that it can stop ANR.
6426 */
6427void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6428 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006429 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006430 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006431 pid = findMonitorPidByTokenLocked(connectionToken);
6432 } else {
6433 // The connection is a window
6434 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6435 if (handle != nullptr) {
6436 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006437 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006438 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006439 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006440}
6441
Prabir Pradhan24047542023-11-02 17:14:59 +00006442std::unique_ptr<const KeyEntry> InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006443 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006444 const KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006445 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006446 if (!handled) {
6447 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006448 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006449 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006450 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006452
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006453 // Get the fallback key state.
6454 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006455 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006457 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006458 connection->inputState.removeFallbackKey(originalKeyCode);
6459 }
6460
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006461 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006462 // If the application handles the original key for which we previously
6463 // generated a fallback or if the window is not a foreground window,
6464 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006466 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006467 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6468 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6469 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6470 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6471 keyEntry.policyFlags);
6472 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006473 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006474 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475
6476 mLock.unlock();
6477
Prabir Pradhana41d2442023-04-20 21:30:40 +00006478 if (const auto unhandledKeyFallback =
6479 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6480 event, keyEntry.policyFlags);
6481 unhandledKeyFallback) {
6482 event = *unhandledKeyFallback;
6483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484
6485 mLock.lock();
6486
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006488 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006489 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006490 "application handled the original non-fallback key "
6491 "or is no longer a foreground target, "
6492 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006493 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006494 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006496 connection->inputState.removeFallbackKey(originalKeyCode);
6497 }
6498 } else {
6499 // If the application did not handle a non-fallback key, first check
6500 // that we are in a good state to perform unhandled key event processing
6501 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006502 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006503 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006504 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6505 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6506 "since this is not an initial down. "
6507 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6508 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6509 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006510 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006513 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006514 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6515 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6516 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6517 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6518 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006519 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006520
6521 mLock.unlock();
6522
Prabir Pradhana41d2442023-04-20 21:30:40 +00006523 bool fallback = false;
6524 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6525 event, keyEntry.policyFlags);
6526 fb) {
6527 fallback = true;
6528 event = *fb;
6529 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006530
6531 mLock.lock();
6532
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006533 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006534 connection->inputState.removeFallbackKey(originalKeyCode);
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006535 return {};
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006536 }
6537
6538 // Latch the fallback keycode for this key on an initial down.
6539 // The fallback keycode cannot change at any other point in the lifecycle.
6540 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006542 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006543 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006544 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006545 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006546 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006547 }
6548
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006549 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006550
6551 // Cancel the fallback key if the policy decides not to send it anymore.
6552 // We will continue to dispatch the key to the policy but we will no
6553 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006554 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6555 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006556 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6557 if (fallback) {
6558 ALOGD("Unhandled key event: Policy requested to send key %d"
6559 "as a fallback for %d, but on the DOWN it had requested "
6560 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006561 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006562 } else {
6563 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6564 "but on the DOWN it had requested to send %d. "
6565 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006566 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006567 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006568 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006569
Michael Wrightfb04fd52022-11-24 22:31:11 +00006570 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006571 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006572 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006573 synthesizeCancelationEventsForConnectionLocked(connection, options);
6574
6575 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006576 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006577 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006578 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006579 }
6580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6583 {
6584 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006585 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006586 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006587 for (const auto& [key, value] : fallbackKeys) {
6588 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006589 }
6590 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6591 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006593 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006594
6595 if (fallback) {
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006596 // Return the fallback key that we want dispatched to the channel.
6597 std::unique_ptr<KeyEntry> newEntry =
6598 std::make_unique<KeyEntry>(mIdGenerator.nextId(), keyEntry.injectionState,
6599 event.getEventTime(), event.getDeviceId(),
6600 event.getSource(), event.getDisplayId(),
6601 keyEntry.policyFlags, keyEntry.action,
6602 event.getFlags() | AKEY_EVENT_FLAG_FALLBACK,
6603 *fallbackKeyCode, event.getScanCode(),
6604 event.getMetaState(), event.getRepeatCount(),
6605 event.getDownTime());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006606 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6607 ALOGD("Unhandled key event: Dispatching fallback key. "
6608 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006609 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006610 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006611 return newEntry;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006612 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006613 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6614 ALOGD("Unhandled key event: No fallback key.");
6615 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006616
6617 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006618 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619 }
6620 }
Prabir Pradhanb9dd1642023-11-02 18:05:36 +00006621 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622}
6623
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624void InputDispatcher::traceInboundQueueLengthLocked() {
6625 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006626 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006627 }
6628}
6629
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006630void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 if (ATRACE_ENABLED()) {
6632 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006633 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6634 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 }
6636}
6637
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006638void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639 if (ATRACE_ENABLED()) {
6640 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006641 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6642 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643 }
6644}
6645
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006646void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006647 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006648
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006649 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006650 dumpDispatchStateLocked(dump);
6651
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006652 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006653 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006654 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006655 }
6656}
6657
6658void InputDispatcher::monitor() {
6659 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006660 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006661 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006662 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663}
6664
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006665/**
6666 * Wake up the dispatcher and wait until it processes all events and commands.
6667 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6668 * this method can be safely called from any thread, as long as you've ensured that
6669 * the work you are interested in completing has already been queued.
6670 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006671bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006672 /**
6673 * Timeout should represent the longest possible time that a device might spend processing
6674 * events and commands.
6675 */
6676 constexpr std::chrono::duration TIMEOUT = 100ms;
6677 std::unique_lock lock(mLock);
6678 mLooper->wake();
6679 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6680 return result == std::cv_status::no_timeout;
6681}
6682
Vishnu Naire798b472020-07-23 13:52:21 -07006683/**
6684 * Sets focus to the window identified by the token. This must be called
6685 * after updating any input window handles.
6686 *
6687 * Params:
6688 * request.token - input channel token used to identify the window that should gain focus.
6689 * request.focusedToken - the token that the caller expects currently to be focused. If the
6690 * specified token does not match the currently focused window, this request will be dropped.
6691 * If the specified focused token matches the currently focused window, the call will succeed.
6692 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6693 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6694 * when requesting the focus change. This determines which request gets
6695 * precedence if there is a focus change request from another source such as pointer down.
6696 */
Vishnu Nair958da932020-08-21 17:12:37 -07006697void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6698 { // acquire lock
6699 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006700 std::optional<FocusResolver::FocusChanges> changes =
6701 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6702 if (changes) {
6703 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006704 }
6705 } // release lock
6706 // Wake up poll loop since it may need to make new input dispatching choices.
6707 mLooper->wake();
6708}
6709
Vishnu Nairc519ff72021-01-21 08:23:08 -08006710void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6711 if (changes.oldFocus) {
6712 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006713 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006714 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006715 "focus left window");
6716 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006717 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006718 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006719 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006720 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006721 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006722 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006723 }
6724
Prabir Pradhan99987712020-11-10 18:43:05 -08006725 // If a window has pointer capture, then it must have focus. We need to ensure that this
6726 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6727 // If the window loses focus before it loses pointer capture, then the window can be in a state
6728 // where it has pointer capture but not focus, violating the contract. Therefore we must
6729 // dispatch the pointer capture event before the focus event. Since focus events are added to
6730 // the front of the queue (above), we add the pointer capture event to the front of the queue
6731 // after the focus events are added. This ensures the pointer capture event ends up at the
6732 // front.
6733 disablePointerCaptureForcedLocked();
6734
Vishnu Nairc519ff72021-01-21 08:23:08 -08006735 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006736 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006737 }
6738}
Vishnu Nair958da932020-08-21 17:12:37 -07006739
Prabir Pradhan99987712020-11-10 18:43:05 -08006740void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006741 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006742 return;
6743 }
6744
6745 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6746
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006747 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006748 setPointerCaptureLocked(false);
6749 }
6750
6751 if (!mWindowTokenWithPointerCapture) {
6752 // No need to send capture changes because no window has capture.
6753 return;
6754 }
6755
6756 if (mPendingEvent != nullptr) {
6757 // Move the pending event to the front of the queue. This will give the chance
6758 // for the pending event to be dropped if it is a captured event.
6759 mInboundQueue.push_front(mPendingEvent);
6760 mPendingEvent = nullptr;
6761 }
6762
6763 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006764 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006765 mInboundQueue.push_front(std::move(entry));
6766}
6767
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006768void InputDispatcher::setPointerCaptureLocked(bool enable) {
6769 mCurrentPointerCaptureRequest.enable = enable;
6770 mCurrentPointerCaptureRequest.seq++;
6771 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006772 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006773 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006774 };
6775 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006776}
6777
Vishnu Nair599f1412021-06-21 10:39:58 -07006778void InputDispatcher::displayRemoved(int32_t displayId) {
6779 { // acquire lock
6780 std::scoped_lock _l(mLock);
6781 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006782 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006783 setFocusedApplicationLocked(displayId, nullptr);
6784 // Call focus resolver to clean up stale requests. This must be called after input windows
6785 // have been removed for the removed display.
6786 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006787 // Reset pointer capture eligibility, regardless of previous state.
6788 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006789 // Remove the associated touch mode state.
6790 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006791 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006792 } // release lock
6793
6794 // Wake up poll loop since it may need to make new input dispatching choices.
6795 mLooper->wake();
6796}
6797
Patrick Williamsd828f302023-04-28 17:52:08 -05006798void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
Siarhei Vishniakouaeed0da2024-01-09 08:57:13 -08006799 if (auto result = validateWindowInfosUpdate(update); !result.ok()) {
6800 {
6801 // acquire lock
6802 std::scoped_lock _l(mLock);
6803 logDispatchStateLocked();
6804 }
6805 LOG_ALWAYS_FATAL("Incorrect WindowInfosUpdate provided: %s",
6806 result.error().message().c_str());
6807 };
chaviw15fab6f2021-06-07 14:15:52 -05006808 // The listener sends the windows as a flattened array. Separate the windows by display for
6809 // more convenient parsing.
6810 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006811 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006812 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006813 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006814 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006815
6816 { // acquire lock
6817 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006818
6819 // Ensure that we have an entry created for all existing displays so that if a displayId has
6820 // no windows, we can tell that the windows were removed from the display.
6821 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6822 handlesPerDisplay[displayId];
6823 }
6824
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006825 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006826 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006827 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6828 }
6829
6830 for (const auto& [displayId, handles] : handlesPerDisplay) {
6831 setInputWindowsLocked(handles, displayId);
6832 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006833
6834 if (update.vsyncId < mWindowInfosVsyncId) {
6835 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6836 ", current update vsync id: %" PRId64,
6837 mWindowInfosVsyncId, update.vsyncId);
6838 }
6839 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006840 }
6841 // Wake up poll loop since it may need to make new input dispatching choices.
6842 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006843}
6844
Vishnu Nair062a8672021-09-03 16:07:44 -07006845bool InputDispatcher::shouldDropInput(
6846 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006847 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6848 (windowHandle->getInfo()->inputConfig.test(
6849 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006850 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006851 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6852 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006853 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006854 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006855 windowHandle->getInfo()->displayId);
6856 return true;
6857 }
6858 return false;
6859}
6860
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006861void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006862 const gui::WindowInfosUpdate& update) {
6863 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006864}
6865
Arthur Hungdfd528e2021-12-08 13:23:04 +00006866void InputDispatcher::cancelCurrentTouch() {
6867 {
6868 std::scoped_lock _l(mLock);
6869 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006870 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006871 "cancel current touch");
6872 synthesizeCancelationEventsForAllConnectionsLocked(options);
6873
6874 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006875 }
6876 // Wake up poll loop since there might be work to do.
6877 mLooper->wake();
6878}
6879
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006880void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6881 std::scoped_lock _l(mLock);
6882 mMonitorDispatchingTimeout = timeout;
6883}
6884
Arthur Hungc539dbb2022-12-08 07:45:36 +00006885void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6886 const sp<WindowInfoHandle>& oldWindowHandle,
6887 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006888 TouchState& state, int32_t deviceId,
6889 const PointerProperties& pointerProperties,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006890 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006891 std::vector<PointerProperties> pointers{pointerProperties};
Arthur Hungc539dbb2022-12-08 07:45:36 +00006892 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6893 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6894 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6895 newWindowHandle->getInfo()->inputConfig.test(
6896 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6897 const sp<WindowInfoHandle> oldWallpaper =
6898 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6899 const sp<WindowInfoHandle> newWallpaper =
6900 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6901 if (oldWallpaper == newWallpaper) {
6902 return;
6903 }
6904
6905 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006906 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006907 addPointerWindowTargetLocked(oldWallpaper, InputTarget::DispatchMode::SLIPPERY_EXIT,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006908 oldTouchedWindow.targetFlags, getPointerIds(pointers),
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006909 oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006910 state.removeTouchingPointerFromWindow(deviceId, pointerProperties.id, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006911 }
6912
6913 if (newWallpaper != nullptr) {
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006914 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::SLIPPERY_ENTER,
6915 InputTarget::Flags::WINDOW_IS_OBSCURED |
Arthur Hungc539dbb2022-12-08 07:45:36 +00006916 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006917 deviceId, pointers);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006918 }
6919}
6920
6921void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6922 ftl::Flags<InputTarget::Flags> newTargetFlags,
6923 const sp<WindowInfoHandle> fromWindowHandle,
6924 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006925 TouchState& state, int32_t deviceId,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006926 const std::vector<PointerProperties>& pointers) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006927 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6928 fromWindowHandle->getInfo()->inputConfig.test(
6929 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6930 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6931 toWindowHandle->getInfo()->inputConfig.test(
6932 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6933
6934 const sp<WindowInfoHandle> oldWallpaper =
6935 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6936 const sp<WindowInfoHandle> newWallpaper =
6937 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6938 if (oldWallpaper == newWallpaper) {
6939 return;
6940 }
6941
6942 if (oldWallpaper != nullptr) {
6943 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6944 "transferring touch focus to another window");
6945 state.removeWindowByToken(oldWallpaper->getToken());
6946 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6947 }
6948
6949 if (newWallpaper != nullptr) {
6950 nsecs_t downTimeInTarget = now();
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006951 ftl::Flags<InputTarget::Flags> wallpaperFlags = oldTargetFlags & InputTarget::Flags::SPLIT;
Arthur Hungc539dbb2022-12-08 07:45:36 +00006952 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6953 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan4b09c1f2023-11-17 03:16:25 +00006954 state.addOrUpdateWindow(newWallpaper, InputTarget::DispatchMode::AS_IS, wallpaperFlags,
Siarhei Vishniakou1ff00cc2023-12-13 16:12:13 -08006955 deviceId, pointers, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006956 std::shared_ptr<Connection> wallpaperConnection =
6957 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006958 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006959 std::shared_ptr<Connection> toConnection =
6960 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006961 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6962 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6963 wallpaperFlags);
6964 }
6965 }
6966}
6967
6968sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6969 const sp<WindowInfoHandle>& windowHandle) const {
6970 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6971 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6972 bool foundWindow = false;
6973 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6974 if (!foundWindow && otherHandle != windowHandle) {
6975 continue;
6976 }
6977 if (windowHandle == otherHandle) {
6978 foundWindow = true;
6979 continue;
6980 }
6981
6982 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6983 return otherHandle;
6984 }
6985 }
6986 return nullptr;
6987}
6988
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006989void InputDispatcher::setKeyRepeatConfiguration(std::chrono::nanoseconds timeout,
6990 std::chrono::nanoseconds delay) {
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006991 std::scoped_lock _l(mLock);
6992
Siarhei Vishniakoufa2a0492023-11-14 13:13:18 -08006993 mConfig.keyRepeatTimeout = timeout.count();
6994 mConfig.keyRepeatDelay = delay.count();
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006995}
6996
Prabir Pradhan64f21d22023-11-28 21:19:42 +00006997bool InputDispatcher::isPointerInWindow(const sp<android::IBinder>& token, int32_t displayId,
6998 DeviceId deviceId, int32_t pointerId) {
6999 std::scoped_lock _l(mLock);
7000 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
7001 if (touchStateIt == mTouchStatesByDisplay.end()) {
7002 return false;
7003 }
7004 for (const TouchedWindow& window : touchStateIt->second.windows) {
7005 if (window.windowHandle->getToken() == token &&
7006 (window.hasTouchingPointer(deviceId, pointerId) ||
7007 window.hasHoveringPointer(deviceId, pointerId))) {
7008 return true;
7009 }
7010 }
7011 return false;
7012}
7013
Garfield Tane84e6f92019-08-29 17:28:41 -07007014} // namespace android::inputdispatcher